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) { string maxS,minS; if(a.size()>b.size()) { maxS = a; minS = b; } else { maxS = b; minS = a; } int len1,len2; len1 = maxS.size(); len2 = minS.size(); int flag = 0; string res(len1+1,'0'); int i = len1-1; int j = len2-1; int z = len1; while(j>=0) { int num = maxS[i--]-'0'+minS[j--]-'0'+flag; if(num>=2) { num -= 2; flag = 1; } else { flag = 0; } res[z--] = num + '0'; } while(i>=0) { int num = maxS[i--]-'0'+flag; if(num>=2) { num -= 2; flag = 1; } else { flag = 0; } res[z--] = num + '0'; } if(flag == 1) { res[z] = '1'; return res; } else { return res.substr(1); } } };