二进制加法代码2
#include<iostream> using namespace std; int* sum_binary_array(bool *a,bool *b,int n) { int *c=new int[n+1]; int flag=0,key=0; for(int i=0;i<n;++i) { key=a[i]+b[i]+flag; c[i]=key%2; if(key>1) flag=1; else flag=0; } if(flag==1) c[n]=1; 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; }