Python easy to understand 45ms


  • 0
    K
    class Solution(object):
        def addBinary(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            
            rem = 0
            
            if len(a) >= len(b):
                larg, short = a, b    
            else:
                larg, short = b, a
                            
            # Going from the back of the strings to the front, checking with if statements to perform the simple math
                
            for x in range(0,len(larg)):
                if x < len(short):
                    if short[len(short)-x-1] == "1" and larg[len(larg)-x-1] == "1":
                        if rem == 1:
                            larg = larg[:len(larg)-x-1] + "1" + larg[len(larg)-x-1+1:]
                        else:
                            larg = larg[:len(larg)-x-1] + "0" + larg[len(larg)-x-1+1:]
                        rem = 1
                    else:
                        if short[len(short)-x-1] == "1" or larg[len(larg)-x-1] == "1":
                            if rem == 1:
                                larg = larg[:len(larg)-x-1] + "0" + larg[len(larg)-x-1+1:]
                                rem = 1
                            else:
                                larg = larg[:len(larg)-x-1] + "1" + larg[len(larg)-x-1+1:]
                                rem = 0
                        elif rem == 1:
                            larg  = larg[:len(larg)-x-1] + "1" + larg[len(larg)-x-1+1:]
                            rem = 0
                else:
                    if rem == 1:
                        if larg[len(larg)-x-1] == "1":
                            larg  = larg[:len(larg)-x-1] + "0" + larg[len(larg)-x-1+1:]
                        else:
                            larg  = larg[:len(larg)-x-1] + "1" + larg[len(larg)-x-1+1:]
                            rem = 0
                    else:
                        break
                        
            if rem == 1:
                larg = "1" + larg
            
            return larg
    

Log in to reply
 

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