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 n = a.length();
int m = b.length();
int i = n-1;
int j = m-1;
string s;
int x = 0;
int y = 0;
int z = 0;
while((i > -1)||(j > -1))
{
if(i <= -1)x = 0;
else if(a[i] == '1')x = 1;
else x= 0;
if(j <= -1)y = 0;
else if(b[j] == '1')y = 1;
else y= 0;
int sum = x+y+z;
if(sum == 3)
{
s = "1"+s;
z = 1;
}
else if(sum == 2)
{
s = "0"+s;
z = 1;
}
else if(sum == 1)
{
s = "1"+s;
z = 0;
}
else
{
s = "0"+s;
z = 0;
}
i--;
j--;
}
if(z == 1)s = "1"+s;
return s;
}
};