Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Subscribe to see which companies asked this question
class Solution {
public:
string addBinary(string a, string b) {
int aLen = a.length(), bLen = b.length(), i=0, index=0;
if(aLen == 0) return b;
if(bLen == 0) return a;
if(aLen < bLen) return addBinary(b, a);
int cnt=0;
for(i = bLen-1, index=aLen-1; i >= 0; i--, index--) {
int temp = a[index]-'0'+b[i]-'0'+cnt;
cnt = temp/2;
temp = temp%2;
a[index] = '0'+temp;
}
for(; index >= 0; index--) {
int temp = a[index]-'0'+cnt;
cnt = temp/2;
temp = temp%2;
a[index] = '0'+temp;
}
if(cnt > 0) {
a = '1'+a;
}
return a;
}
};