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”
C++
string addBinary(string a, string b) {
int len1 = a.size() - 1;
int len2 = b.size() - 1;
string s = "";
int carry = 0;
while(len1 >= 0||len2 >= 0||carry == 1)
{
int temp = len1 >= 0 ? (a[len1--] - '0') : 0;
temp += len2 >= 0 ? (b[len2--] - '0') : 0;
temp += carry;
carry = temp / 2;
temp = temp % 2;
s = char('0' + temp) + s;
}
return s;
}