Python solution without integer conversion


  • 0
    G

    I don't think that the goal of this exercice was to convert the binary string to an integer as I see in most solutions. Here is my solution which use the algorithm of the addition.

    class Solution(object):
        def addBinary(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            a = list(map(int, a))
            b = list(map(int, b))
            addition_table = { # (digit_1, digit_2, carry) : (result, new_carry)
                (0, 0, 0) : (0, 0),
                (0, 0, 1) : (1, 0),
                (0, 1, 0) : (1, 0),
                (1, 0, 0) : (1, 0),
                (0, 1, 1) : (0, 1),
                (1, 0, 1) : (0, 1),
                (1, 1, 0) : (0, 1),
                (1, 1, 1) : (1, 1)
            }
            
            result = []
            carry = 0
            i = len(a) - 1
            j = len(b) - 1
            
            while i >= 0 or j >= 0 or carry:
                digit_1 = a[i] if i >= 0 else 0 
                digit_2 = b[j] if j >= 0 else 0
                res, carry = addition_table[(digit_1, digit_2, carry)]
                result.append(res)
                i -= 1
                j -= 1
            
            return ''.join(map(str, reversed(result))) 
    

Log in to reply
 

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