Simple Python Solution 76ms


  • 6
    T

    I assume using int and str is okay, I think this is easy to understand.

    def addBinary(self, a, b):
        result = ''
        index = 0
        
        carry = '0'
        while index < max(len(a), len(b)) or carry == '1':
            num_a = a[-1 - index] if index < len(a) else '0'
            num_b = b[-1 - index] if index < len(b) else '0'
            
            val = int(num_a) + int(num_b) + int(carry)
            result = str(val % 2) + result
            
            carry = '1' if val > 1 else '0'
            index += 1
    
        return result
    

    ================== update ===============

    No int and str version.

    class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    # 75ms
    def addBinary(self, a, b):
        result = ''
        index = 0
        
        carry = '0'
        while index < max(len(a), len(b)) or carry == '1':
            num_a = a[-1 - index] if index < len(a) else '0'
            num_b = b[-1 - index] if index < len(b) else '0'
            
            val = self.to_int(num_a) + self.to_int(num_b) + self.to_int(carry)
            result = "%s%s" % (val % 2, result)
            
            carry = '1' if val > 1 else '0'
            index += 1
    
        return result
    
    def to_int(self, c):
        if c == '1':
            return 1
        elif c == '0':
            return 0

  • 0
    B
    This post is deleted!

  • 5
    B

    if int() function is allowed, the following code may be more simple. :)

    def addBinary(self, a, b):
            a = int(a, 2)
            b = int(b, 2)
            return ("" + bin(a+b))[2:]
    

  • 0
    T

    well, using int in that way is different right, actually we can easily remove the build-in int here, I will update my code.


  • 0
    A

    if the string is long, doing a+b as int may cause overflow


Log in to reply
 

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