Simple Python solution

  • 0
    class Solution:
        # @param a, a string
        # @param b, a string
        # @return a string
        def addBinary(self, a, b):
            d = len(a)-len(b)
            if d>0:
                b = d*'0'+b
                a = (-d)*'0'+a
            res = ''
            f = '0'
            for i in range(len(a)-1,-1,-1):
                f,r = self.add(a[i],b[i],f)
                res = r+res
            res = f + res
            return res.lstrip('0') or '0'
        def add(self,a,b,flag):
            n = (a+b+flag).count('1')
            if n>=2:
                return ('1',str(n-2))
                return ('0',str(n))

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.