my python code, any idea to improve?


  • 0
    F

    #complement to the same length and sum
    '''
    la = len(a)
    lb = len(b)

        while( la > lb):
            b = '0' + b
            lb += 1
        while (la < lb):
            a = '0' + a
            la += 1
            
        c = 0
        r = ""
        i = la-1
        while(i >= 0):
            e1 =int(a[i])
            e2 = int(b[i])
            
            d = (e1 + e2 + c)%2
            c = (e1 + e2 + c)/2
            r = str(d) + r
            i -= 1
        if  c == 1:
            r = str(c) + r
        return r
    

    '''


  • 0
    K

    My simple Python solution

    class Solution(object):
        def addBinary(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            if len(set(a))>2 or len(set(b))>2:
                return '0'
            res = bin(int('0b'+a,2)+int('0b'+b,2))  #int(a,2)可将2进制转为10进制!!
            return res[2:]
    

Log in to reply
 

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