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)
{
int lena = a.size();
int lenb = b.size();
int i,j;
if(lena==0||lenb==0)return a+b;
string str;
int carry = 0;
int tem;
for(i=lena-1, j=lenb-1;i>=0&&j>=0;i--,j--)
{
tem = (a[i]+b[j]+carry-2*'0')%2;
carry = (a[i]+b[j]+carry-2*'0')/2;
str = (char)(tem + '0') + str;
}
if(i>=0)
{
while(i!=-1)
{
tem = (a[i]+carry-'0')%2;
carry = (a[i]+carry-'0')/2;
str = (char)(tem + '0') + str;
i--;
}
}
if(j>=0)
{
while(j!=-1)
{
tem = (b[j]+carry-'0')%2;
carry = (b[j]+carry-'0')/2;
str = (char)(tem + '0') + str;
j--;
}
}
if(carry==1)
str = '1'+str;
return str;
}
};