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 i1 = a.size() - 1, i2 = b.size() - 1;
int tmp = 0, sum;
string str;
while (i1 >= 0 && i2 >= 0)
{
sum = a[i1] - '0' + b[i2] - '0' + tmp;
str.push_back(sum % 2 + '0');
tmp = sum / 2;
--i1;
--i2;
}
while (i1 >= 0)
{
sum = a[i1] - '0' + tmp;
str.push_back(sum % 2 + '0');
tmp = sum / 2;
--i1;
}
while (i2 >= 0)
{
sum = b[i2] - '0' + tmp;
str.push_back(sum % 2 + '0');
tmp = sum / 2;
--i2;
}
if (tmp)
str.push_back(tmp + '0');
reverse(str.begin(), str.end());
if(str.empty())
str.push_back('0');
return str;
}