Python solution with traversal not recursive


  • 0
    K
    class Solution(object):
        def addBinary(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            res = []
            if len(a) < len(b):
                a, b = b, a
            len_a = len(a)
            len_b = len(b)
            carry = 0
            for i in xrange(len(a)):
                if i < len_b:
                    tmp = int(a[len_a - 1 - i]) + int(b[len_b - 1 - i]) + carry
                else:
                    tmp = int(a[len_a - 1 - i]) + carry
                res = [str(tmp % 2)] + res
                carry = tmp / 2
            if carry:
                res = [str(carry)] + res
            return ''.join(res)
    

Log in to reply
 

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