67-add-binary

Try it on leetcode

Description

Given two binary strings a and b, return their sum as a binary string.

 

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

 

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

Solution(Python)

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        max_len = max(len(a), len(b))

        a = a.zfill(max_len)
        b = b.zfill(max_len)

        # initialize the result
        result = ""

        # initialize the carry
        carry = 0

        # Traverse the string
        for i in range(max_len - 1, -1, -1):
            digit = int((carry + int(a[i]) + int(b[i])) % 2)
            result = str(digit) + result
            carry = int((carry + int(a[i]) + int(b[i])) // 2)

        if carry != 0:
            result = "1" + result

        return result.zfill(max_len)