Python code can not pass OJ but which pass on local


  • 0
    M
    class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
        maxLen = max(len(a), len(b))
        result = [0] * maxLen
        if len(a) > len(b):
            tempB = '0' * (len(a)-len(b)) + b
            tempA = a
        else:
            tempA = '0' * (len(b)-len(a)) + a
            tempB = b
        for i in range(maxLen-1, -1, -1):
            x = int(tempA[i]) + int(tempB[i])
            if x == 2 or x == 0:
                pass
            else:
                result[i] += 1
        if result[0] == 0:
            result.insert(0, 1)
        return ''.join(str(e) for e in result)
    

    which failed the case('0', '0'), gave an wrong answer '0',
    Actually on local, which output the correct answer '10'.


  • 0
    D

    Your code is not correct. 0 + 0 should be 0, not 10 ^_^. However, I've modified your code to be accepted by oj. But still, you need to work on it .

    class Solution:
        # @param a, a string
        # @param b, a string
        # @return a string
        def addBinary(self, a, b):
            maxLen = max(len(a), len(b))
            result = [0] * maxLen
            if len(a) > len(b):
                tempB = '0' * (len(a)-len(b)) + b
                tempA = a
            else:
                tempA = '0' * (len(b)-len(a)) + a
                tempB = b
                
            x = 0 #x is carry 
            for i in range(maxLen-1, -1, -1):
                x += int(tempA[i]) + int(tempB[i]) #changed
                if x == 2 or x == 0:
                    pass
                else:
                    result[i] = 1
                    
                x = 1 if x>1 else 0 #added
            if x == 1: #changed
                result.insert(0, 1)
            return ''.join(str(e) for e in result)

  • 0
    M

    Oops, how stupid am I, -_-!! (treated this as "Plus One")
    Sorry for asking such an idiotic question~
    Thanks for your kindly reminding~


Log in to reply
 

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