Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
//#67 Add Binary
//172ms 0.47%
class Solution {
public:
string addBinary(string a, string b)
{
string result;
int i(a.size()-1), j(b.size()-1);
int carry(0);
while(i >= 0 || j >=0)
{
int num1 = (i >= 0)? a[i] - '0' : 0;
int num2 = (j >= 0)? b[j] - '0' : 0;
cout << num1 << ", " << num2 << endl;
int num = (num1 + num2 + carry) % 2;
carry = (num1 + num2 + carry) / 2;
cout << num << ", " << carry << endl;
result.insert(result.begin(), num + '0');
i --;
j --;
}
if(carry == 1)
{
result.insert(result.begin(), '1');
}
return result;
}
};