SDE & MLE Prep

67. Add Binary

Problem

Return the sum of two binary strings a and b as a binary string.

Example: "11" + "1" → "100"; "1010" + "1011" → "10101"

Add from the right with a carry, like decimal addition in base 2.

Complexity: O(max(m, n)).

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        i, j, carry, out = len(a) - 1, len(b) - 1, 0, []
        while i >= 0 or j >= 0 or carry:
            s = carry + (int(a[i]) if i >= 0 else 0) + (int(b[j]) if j >= 0 else 0)
            out.append(str(s % 2))
            carry = s // 2
            i, j = i - 1, j - 1
        return "".join(reversed(out))