Recursive Python code


  • 0
    W
    class Solution(object):
        def addBinary(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            def add(a,b,res):
                if len(a) == len(b) == 0:
                    if res == 0:
                        return ''
                    if res == 1:
                        return '1'
                if len(a) == 0:
                    return add('0',b,res) + ''
                if len(b) == 0:
                    return add(a,'0',res) + ''
                if a[-1] == '1' and b[-1] == '1':
                    if res == 1:
                        return add(a[0:-1],b[0:-1],res) + '1'
                    else:
                        res = 1
                        return add(a[0:-1],b[0:-1],res) + '0'
                elif (a[-1] == '0' and b[-1] == '1') or (a[-1] == '1' and b[-1] == '0'):
                    if res == 1:
                        return add(a[0:-1],b[0:-1],res) + '0'
                    else:
                        return add(a[0:-1],b[0:-1],res) + '1'
                else:
                    if res == 0:
                        return add(a[0:-1],b[0:-1],res) + '0'
                    else:
                        res = 0
                        return add(a[0:-1],b[0:-1],res) + '1'
            s = add(a,b,0)
            return s
    

Log in to reply
 

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