Given two binary strings, return their sum (also a binary string). For example, a = "11",
b = "1"
Return "100"
.
string addBinary(string a, string b) {
int carry = 0;
int len1 = a.length();
int len2 = b.length();
int len = max(len1, len2);
string c;
for(int i=0; i<len; i++ )
{
int ch1 = (i<len1)?a.at(len1-1-i)-'0':0;
int ch2 = (i<len2)?b.at(len2-1-i)-'0':0;
int sum = (ch1+ch2+carry)%2;
carry = (ch1+ch2+carry)/2;
c = to_string(sum)+c; // to_string converts an integer into a string
}
if(carry>0)
c = to_string(carry)+c;
return c;
}