Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
看起来挺好写的样子,没想到墨迹了半天。
string add(string a, string b,int lena,int lenb) { if(lena<lenb) return add(b,a,lenb,lena); //lena>=lenb int cf=0; int i=0,j=0; int ia=0,ib=0,csum=0; for(i=lena-1,j=lenb-1;j>=0;i--,j--) { ia=a[i]-‘0‘; ib=b[j]-‘0‘; if(cf) csum=ia+ib+cf; else csum=ia+ib; if(csum>=2) { cf=1; csum=csum-2; } else cf=0; a[i]=csum+‘0‘; } while(cf&&i>=0) { ia=a[i]-‘0‘; csum = ia+cf; if(csum>=2) { csum=csum-2; cf=1; } else { cf=0; } a[i]=csum+‘0‘; i--; } if(cf) a.insert(a.begin(),‘1‘); return a; } string addBinary(string a, string b) { if(a=="" && b=="") return ""; else if(a=="") return b; else if (b=="") return a; else { int lena=a.size(),lenb=b.size(); string s=add(a,b,lena,lenb); return s; } }
去看看有什么别人的方法:
先进行对齐补零,这样比我少了一点麻烦,没想到。。。。
看代码:
string addBinary(string a, string b) { int sizea = a.size(); int sizeb = b.size(); if(sizea < sizeb) return addBinary(b, a); //sizea >= sizeb string zeros(sizea-sizeb, ‘0‘); b = zeros + b; int carry = 0; for(int i = sizea-1; i >= 0; i --) { int sum = (a[i]-‘0‘) + (b[i] - ‘0‘) + carry; if(sum == 0) ; else if(sum == 1) { a[i] = ‘1‘; carry = 0; } else if(sum == 2) { a[i] = ‘0‘; carry = 1; } else {//sum == 3 (1+1+1) a[i] = ‘1‘; carry = 1; } } if(carry == 1) a = "1" + a; return a; }
时间: 2024-11-14 08:25:22