Python Solution for Reverse Integer with no overflow handling


  • 4
    A

    This is my code:

    class Solution:
    # @param {integer} x
    # @return {integer}
    def reverse(self, x):
        arr = []
        f = False
        if x < 0:
            x *= -1
            f = True
        while True:
            arr.append(x % 10)
            x /= 10
            if x == 0:
                break
        result = 0
        for i in arr:
            result = i + 10 * result
        if f:
            result *= -1
        return result
    

    Actually python wouldn't overflow, but the test cases consider it.
    When Input is1534236469 and my output is 9646324351,it says wrong.:-(


  • 1
    W

    I had the same issue in JS, i had to add an if statement that checked if the number was over 2147483647 and return 0 if so.


  • 0
    F

    I have the same problem.
    If you treat it like string, the reverse would never overflow.


  • 0
    L

    I had same annouing issue, althoug the code I used was way shorter than yours. I agree it is annoying.

        if x>=0:
            test=str(x)
            test2=test[::-1]
        else:
            test=str(abs(x))
            test=test+('-')
            test2=test[::-1]
        
        return int(test2)

  • 0
    L

    @Lexa_Ville Just to add. If I add this condition at the end of my code it is accepted:

    if int(test2)>2147483647:
                test2='0'
    if int(test2)<-2147483648:
                test2='0'

Log in to reply
 

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