Problem
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string strResult;
int idxA = a.size() - 1;
int idxB = b.size() - 1;
int carry = 0;
while(idxA >= 0 && idxB >= 0)
{
int sum = a[idxA] - '0' + b[idxB] - '0' + carry;
if (sum == 3)
{
strResult.append("1");
carry = true;
}
else if (sum == 2)
{
strResult.append("0");
carry = true;
}
else if (sum == 1)
{
strResult.append("1");
carry = false;
}
else
{
strResult.append("0");
carry = false;
}
--idxA;
--idxB;
}
if (idxA >=0)
{
while(idxA >= 0)
{
int sum = a[idxA] - '0' + carry;
if (sum == 2)
{
strResult.append("0");
carry = true;
}
else if (sum == 1)
{
strResult.append("1");
carry = false;
}
else
{
strResult.append("0");
carry = false;
}
--idxA;
}
}
else
{
while(idxB >= 0)
{
int sum = b[idxB] - '0' + carry;
if (sum == 2)
{
strResult.append("0");
carry = true;
}
else if (sum == 1)
{
strResult.append("1");
carry = false;
}
else
{
strResult.append("0");
carry = false;
}
--idxB;
}
}
if (carry == 1)
strResult.append("1");
string result(strResult.rbegin(),strResult.rend());
return result;
}
};