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 aLength = a.length() - 1;
int bLength = b.length() - 1;
string res;
int flag = 0;
while(aLength >= 0 && bLength >= 0){
int num = (a[aLength] - '0') + (b[bLength] - '0') + flag;
flag = num / 2;
num %= 2;
res = char(num + '0') + res;
aLength --;
bLength --;
}
while(aLength >= 0){
int num = (a[aLength] - '0') + flag;
flag = num / 2;
num %= 2;
res = char(num + '0') + res;
aLength --;
}
while(bLength >= 0){
int num = (b[bLength] - '0') + flag;
flag = num / 2;
num %= 2;
res = char(num + '0') + res;
bLength --;
}
if(flag > 0)
res = char(flag + '0') + res;
return res;
}
};