Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
class Solution { public: string addBinary(string a, string b) { int aSize = a.size(); int bSize = b.size(); int len = aSize>bSize?aSize+1:bSize+1; string res(len,‘0‘); int k = len-1; int c = 0; int i=aSize-1,j=bSize-1; for(;i>=0 && j>=0;i--,j--){ int tmp = ((a[i]-‘0‘) + (b[j]-‘0‘) + c )%2; c = ((a[i]-‘0‘) + (b[j]-‘0‘) + c )/2; res[k--] = tmp+‘0‘; } while(i>=0){ int tmp = ((a[i]-‘0‘) + c )%2; c = ((a[i]-‘0‘) + c )/2; res[k--] = tmp+‘0‘; i--; } while(j>=0){ int tmp = ((b[j]-‘0‘) + c )%2; c = ((b[j]-‘0‘) + c )/2; res[k--] = tmp+‘0‘; j--; } if(c!=0){ res[k] = c+‘0‘; }else{ res.erase(res.begin(),res.begin()+k+1); } return res; } };
原文:http://www.cnblogs.com/zengzy/p/5002092.html