题目描述
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input:
a = “11”, b = “1”
Output:
“100”
Example 2:
Input:
a = “1010”, b = “1011”
Output:
“10101”
class Solution {
public:
string addBinary(string a, string b) {
string c="";
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
int lena=a.size(), lenb=b.size();
int i=0, j=0, sum=0;
bool carry=false;
while(i<lena || j<lenb){
sum=0;
if(i<lena){
sum += a[i]-'0'; i++;
}
if(j<lenb){
sum += b[j]-'0'; j++;
}
if(carry) sum++;
c += ((sum%2)+'0');
if(sum>=2) carry=true;
else carry=false;
}
if(carry) c += '1';
reverse(c.begin(), c.end());
return c;
}
};