Add Binary
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"
Solution: Using two pointer
We use the carray to store the temp sum and then update the current bit and carray.
string addBinary(string a, string b) {
string ans = "";
int n = a.size()-1, m = b.size()-1, carry = 0;
while (n < a.size() || m < b.size()) {
if (n < a.size()) carry += a[n--] - '0';
if (m < b.size()) carry += b[m--] - '0';
ans = to_string(carry % 2) + ans;
carry = carry / 2;
}
return carry == 1 ? '1' + ans : ans;
}