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 res = "";
int curry = 0;
int i, j;
for (i = a.length() - 1, j = b.length() - 1; i >= 0 && j >= 0; --i, --j)
{
if (((a[i] - '0') + (b[j] - '0')+curry) >=2)
{
res += ((curry + (a[i] - '0') + (b[j] - '0'))%2 + '0');
curry = 1;
}
else
{
res += ((curry+'0' + ((a[i] - '0') + (b[j] - '0')) % 2) % 2 + '0');
curry = 0;
}
}
while (i >= 0)
{
if (((a[i] - '0') + curry) >= 2)
{
res += ((curry + (a[i] - '0')) % 2 + '0');
curry = 1;
}
else
{
res += ((curry + (a[i] - '0')) % 2 + '0');
curry = 0;
}
--i;
}
while (j >= 0)
{
if (((b[j] - '0') + curry) >= 2)
{
res += ((curry + (b[j] - '0')) % 2 + '0');
curry = 1;
}
else
{
res += ((curry + (b[j] - '0')) % 2 + '0');
curry = 0;
}
--j;
}
if (curry == 1)
res += '1';
reverse(res.begin(), res.end());
return res;
}
};