# 67. 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

Approach 1: Do the math add calculation.

# Code (Python)

Approach 1:

# Code (C++)

Approach 1:

class Solution {
public:
    string addBinary(string a, string b) {
        string res = "";
        int carry = 0;
        int aIdx = a.size() - 1;
        int bIdx = b.size() - 1;
        while (aIdx >= 0 || bIdx >= 0)
        {
            int aVal = (aIdx >= 0) ? a[aIdx] - '0' : 0;
            int bVal = (bIdx >= 0) ? b[bIdx] - '0' : 0;
// option 1:
/*
            int sum = aVal + bVal + carry;
            res = char('0' + (sum % 2)) + res;
            carry = sum / 2;
*/
// option 2:
            res = char('0' + aVal ^ bVal ^ carry) + res;
            carry = (aVal && bVal) || (aVal && carry) || (bVal && carry);

            aIdx--;
            bIdx--;
        }
        if (carry > 0)
            res = char('0' + carry) + res;
        return res;
    }
};