leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

67. Add Binary

Open tech-cow opened this issue 5 years ago • 2 comments

tech-cow avatar Feb 10 '20 19:02 tech-cow

First Try:

class Solution(object):
    def addBinary(self, a, b):
        a, b = a[::-1], b[::-1]
        m, n = len(a), len(b)
        diff = max(m, n) - min(m, n)
        
        for i in range(diff):
            if m < n : 
                a += "0"
            else:
                b += "0"
        
        carry = 0
        res = ""
        for i in range(max(m, n)):
            curSum = int(a[i]) + int(b[i]) + carry
            carry = 0
            if curSum == 3:
                carry += 1
                res += "1"
            elif curSum >= 2:
                carry += 1
                res += "0"
            else:
                carry = 0
                res += str(curSum)
        if carry:
            res += str(carry) 
        return res[::-1]

tech-cow avatar Feb 10 '20 19:02 tech-cow

2x Try (1 Day Apart)

class Solution(object):
    def addBinary(self, a, b):
        i = len(a) - 1
        j = len(b) - 1
        
        carry = 0
        res = ""
      
        while i >= 0 or j >= 0 or carry:
            if i >= 0:
                carry += int(a[i])
                i -= 1
            if j >= 0:
                carry += int(b[j])
                j -= 1
            res = str(carry % 2) + res
            carry //= 2
        return res

tech-cow avatar Feb 10 '20 19:02 tech-cow