LC 0067 [E] Add Binary - ALawliet/algorithms GitHub Wiki

exact same idea/format as Add String with some int/str conversion

>>> a = '123'
>>> a.zfill(6)
'000123'

no need for zfill if using pop()

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        res = deque()
        
        t = list(a)
        b = list(b)
        
        carry = 0
        
        while t or b:
            top = bot = 0
            if t:
                top = int(t.pop())
            if b:
                bot = int(b.pop())
                
            carry, drop = divmod(top + bot + carry, 2)
                
            res.appendleft(str(drop))
            
        if carry:
            res.appendleft(str(carry))
                    
        return ''.join(res)
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        ans = deque()
        
        n = max(len(a), len(b))
        a = list(a.zfill(n))
        b = list(b.zfill(n))
        
        carry = 0
        
        while a or b:
            top = bot = 0
            if a.pop() == '1':
                top = 1
            if b.pop() == '1':
                bot = 1
                
            carry, drop = divmod(top + bot + carry, 2)
                
            if drop == 1:
                ans.appendleft('1')
            else:
                ans.appendleft('0')
            
        if carry == 1:
            ans.appendleft('1')
                    
        return ''.join(ans)
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        x = int(a, 2)
        y = int(b, 2)
        while y:
            ans = x ^ y
            carry = (x & y) << 1
            x, y = ans, carry
        return bin(x)[2:]