Python solution


  • 0
    N

    The code uses binary addition property ->
    Add the elements, carry will be the remainder of sum divided by 2 and the sum at that position will be the quotient of the division. So, we just need to keep track of the sum and carry. Additionally, the carry will be added in the next elements' addition. Since any addition starts from the right-most digits, we start traversing both the input numbers from the right until 1 of them gets exhausted.

    After that we continue the process till both of the numbers get exhausted. The result is sum of the digits, but in reverse order. So, we simply reverse the number while returning the result.

    class Solution(object):
        def addBinary(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            len_a = len(a)
            len_b = len(b)
            result = ""
            carry = 0
            while len_a > 0 and len_b > 0:
                sum = int(a[len_a - 1]) + int(b[len_b - 1]) + carry
                carry = sum / 2
                sum = sum % 2
                result += `sum`
                len_a -= 1
                len_b -= 1
                
            while len_a > 0:
                sum = int(a[len_a - 1]) + carry
                carry = sum / 2
                sum = sum % 2
                result += `sum`
                len_a -= 1
    
            while len_b > 0:
                sum = int(b[len_b - 1]) + carry
                carry = sum / 2
                sum = sum % 2
                result += `sum`
                len_b -= 1
    
            if carry > 0:
                result += `carry`
            
            return result[::-1]
                
    

Log in to reply
 

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