Can this Python solution be improved?


  • 0
    X

    Wondering if there's a way to do it with shorter and more elegant code in Python?

    class Solution:
        # @param a, a string
        # @param b, a string
        # @return a string
        def addBinary(self, a, b):
            if a == "" and b == "":
                return ""
            result = ""
            addOne = False
            a = list(a)
            b = list(b)
            while a!=[] and b !=[]:
                ba = int(a.pop())
                bb = int(b.pop())
                num = ba+bb
                if addOne:
                    num += 1
                    addOne = False
                if num >= 2:
                    result += str(num-2)
                    addOne = True
                else:
                    result += str(num)
            while a != []:
                d = int(a.pop())
                if addOne:
                    d += 1
                    addOne = False
                if d >= 2:
                    result += str(d-2)
                    addOne = True
                else:
                    result += str(d)
            while b != []:
                d = int(b.pop())
                if addOne:
                    d += 1
                    addOne = False
                if d >= 2:
                    result += str(d-2)
                    addOne = True
                else:
                    result += str(d)
            if addOne:
                result += "1"
            return result[::-1]

  • 0
    V
    This post is deleted!

  • 0
    I
    This post is deleted!

  • 0
    B

    I have one ,cleaner
    {
    class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
    grade=0
    sum=''
    x=list(a)
    y=list(b)
    while len(x)!=0 or len(y)!=0:
    i=0
    j=0
    if len(x)!=0:
    i=int(x.pop())
    if len(y)!=0:
    j=int(y.pop())
    sum=str((i+j+grade)%2) + sum
    grade=(i+j+grade)/2
    else:
    if grade!=0:
    sum= str(grade)+sum
    return sum
    }


Log in to reply
 

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