将两个输入字符串逆置,从最低位到最高位进行相加,并处理进位情况。
class Solution {
public:
string addBinary(string a, string b)
{
string result;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
const int len1 = a.length();
const int len2 = b.length();
int i, j;
int carry = 0;
int value;
for(i=0,j=0; i<len1 || j<len2; i++,j++)
{
int d1 = i<len1? a[i]-'0':0;
int d2 = j<len2? b[j]-'0':0;
value = (d1+d2+carry)%2;
carry = (d1+d2+carry)/2;
result.insert(result.end(), value+'0');
}
if(carry == 1)
result.insert(result.end(), '1');
reverse(result.begin(), result.end());
return result;
}
};