Python solution - bit manipulation (58 ms, not the best though)


  • 1
    S

    class Solution(object):

     def addBinary(self, a, b):
    
        x = int(a,2)
        y = int(b,2)
        loop = True
        
        while loop:
           
            temp_a = x & y #carry 
            temp_b = x ^ y #sum
            x = temp_a << 1 # shifting the carry for each bit
            y = temp_b
            if( not temp_a): 
                loop = False
                
        return bin(temp_b)[2:]

  • 1
    O

    Why can't you just

    class Solution(object):
        def addBinary(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            return bin(int(a,2) + int(b,2))[2:] 
    

  • 1
    S

    Thanks @Oooseun for the one liner, I appreciate it. I was trying to solve it like an adder with sum and carry instead :) .


Log in to reply
 

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