Back to writing

67. Add Binary

67. Add Binary

Easy


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.

 class Solution:
    def addBinary(self, a: str, b: str) -> str:

        max_len = max(len(a), len(b))
        carry = 0
        a = a.zfill(max_len)
        b = b.zfill(max_len)

        ans = []
        for i in range(max_len-1, -1, -1):
            if a[i] == '1':
                carry+=1
            if b[i] == '1':
                carry+=1

            '''
            if both a, b and c  are 1, c is 3, we'll add 1
            if one of the 3 is 0, c will be 2 % 2 == 0 
            '''
            if carry%2 == 1: # c ==3
                ans.append("1")
            else:
                ans.append("0")
            carry //= 2

        if carry == 1:
            ans.append("1")

        ans.reverse()
        return "".join(ans)

From python 3.7 dict guarantees that order will be kept as they inserted, and popitem will use LIFO order but we need FIFO type system. so we need OrderedDict which have popIten(last = T/F) for this req. One thing, next(iter(dict)) will return the first key of the dict

Python