算法导论2.1-4
源代码奉上
#include<iostream> using namespace std; int* sum_binary_array(bool *a,bool *b,int n) { int *c=new int[n+1]; int sum=0; for(int i=0;i<n;++i) { sum+=a[i]+b[i]; if(sum==2) { if(i!=n-1) { c[i]=0; sum=1; } else { c[i]=0; c[n]=1; } } else { if(i!=n-1) { c[i]=sum; sum=0; } else { c[i]=sum; c[n]=0; } } } return c; } int main() { bool a[]={1,0,1,1},b[]={0,1,1,0}; int *c=sum_binary_array(a,b,4); cout<<" "; for(int i=3;i>=0;--i) cout<<a[i]<<" "; cout<<endl<<" "; for(int i=3;i>=0;--i) cout<<b[i]<<" "; cout<<endl; for(int i=4;i>=0;--i) cout<<c[i]<<" "; cout<<endl; }