Given
two binary strings, return their sum (also a binary string).
class Solution {
public:
string addBinary(
string a,
string b)
{
string c;
reverse(a);
reverse(b);
int size=a.length();
if(b.length()>size) size=b.length();
int add=
0;
for(
int i=
0;i<size;i++)
{
int add1=
0;
int add2=
0;
if(i<a.length()) add1=a[i]-
‘0‘;
if(i<b.length()) add2=b[i]-
‘0‘;
c=c+
char((add1+add2+add)%
2+
‘0‘);
add=(add1+add2+add)/
2;
}
if(add==
1) c=c+
‘1‘;
reverse(c);
return c;
}
void reverse(
string& s)
{
int l=
0;
int r=s.length()-
1;
while(l<r)
{
char tmp=s[l];
s[l]=s[r];
s[r]=tmp;
l++;r--;
}
}
};