My solution using recursion with python


  • -1
    L

    class Solution:

    def addBinaryHelper( self, a, b, carry):
        
        if len(a) == 0:
            if carry == 1:
                return '1'
            else:
                return ''
        
        if carry == 1:
            if a[-1] == '0' and b[-1] == '0':
                return self.addBinaryHelper(a[:-1],b[:-1],0) + '1'
            elif a[-1] == '0' and b[-1] == '1':
                return self.addBinaryHelper(a[:-1],b[:-1],1) + '0'
            elif a[-1] == '1' and b[-1] == '0':
                return self.addBinaryHelper(a[:-1],b[:-1],1) + '0'
            else:
                return self.addBinaryHelper(a[:-1],b[:-1],1) + '1'
        else:
            if a[-1] == '0' and b[-1] == '0':
                return self.addBinaryHelper(a[:-1],b[:-1],0) + '0'
            elif a[-1] == '0' and b[-1] == '1':
                return self.addBinaryHelper(a[:-1],b[:-1],0) + '1'
            elif a[-1] == '1' and b[-1] == '0':
                return self.addBinaryHelper(a[:-1],b[:-1],0) + '1'
            else:
                return self.addBinaryHelper(a[:-1],b[:-1],1) + '0'
                
                
        
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
        if len(a) > len(b):
            b = '0'*(len(a)-len(b)) + b
        elif len(a) < len(b):
            a = '0'*(len(b)-len(a)) + a
            
        if a =='' and b =='':
            return '0'
        return self.addBinaryHelper(a,b,0)

Log in to reply
 

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