题目
代码
class Solution {
public:
string addBinary(string a, string b)
{
int lenA = a.length();
int lenB = b.length();
string result;
int addFlag = 0;
int i;
int current = 0;
for (i = 0;i < lenA&&i < lenB;i++)
{
int numA = a[lenA - i - 1] - '0', numB = b[lenB - i - 1] - '0';
current = (addFlag + numA + numB) % 2;
result.push_back((char)('0' + current));
addFlag = numA + numB + addFlag > 1 ? 1 : 0;
}
if (lenA > lenB)
{
for (;i < lenA;i++)
{
current = ((a[lenA - i - 1] - '0') + addFlag) % 2;
result.push_back('0' + current);
addFlag = a[lenA - i - 1]-'0' + addFlag > 1 ? 1 : 0;
}
if (addFlag == 1)
result.push_back('1');
}
else if (lenA < lenB)
{
for (;i < lenB;i++)
{
current = ((b[lenB - i - 1] - '0') + addFlag) % 2;
result.push_back('0' + current);
addFlag = b[lenB - i - 1]-'0' + addFlag > 1 ? 1 : 0;
}
if (addFlag == 1)
result.push_back('1');
}
else
{
if (addFlag == 1)
result.push_back('1');
}
std::reverse(result.begin(), result.end());
return result;
}
};