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) {
int lena=a.length(),lenb=b.length(),i,carry=0,sum=0;
string ans="";
for(;lena>0||lenb>0;){
sum=carry;
if(lena>0){
sum=sum+a[lena-1]-'0';
lena--;
}
if(lenb>0){
sum=sum+b[lenb-1]-'0';
lenb--;
}
carry=sum/2;
sum=sum%2;
ans=ans+to_string(sum);
}
if(carry){
ans=ans+to_string(carry);
}
reverse(ans.begin(),ans.end());
return ans;
}
};