How to do it faster with Python?


  • 1
    S

    My code:

    MAXINT = 2**31
    
    class Solution:
        def reverse(self, x):
            if x == 0:
                return 0
            sign = x / abs(x)
            x /= sign
            ret = 0
            while x:
                ret *= 10
                ret += x % 10
                x /= 10
            if ret > MAXINT:
                return 0
            return ret * sign
    

    And it costs 204 ms, but I found many Python solutions that uses much less time in the Runtime Distribution. So what method did you use to run faster (of course Python only :D) ?


  • -1
    L

    I just do not use iteration to make the time complexity O(1). Transfer the integer to a string and then reverse it. This takes 87ms

    class Solution:
        # @return an integer
        def reverse(self, x):
            if x >= 0:
                x = str(x)
                x = x[::-1]    #reverse the string
                x = int(x)
                if x < 2**31 - 1:
                    return x
                else:
                    return 0
            else:
                x = str(x)
                x = x[1:]   #Exclude the negative sign
                x = x[::-1]
                x = '-' + x
                x = int(x)
                if x > - 2**31 + 1:
                    return x
                else:
                    return 0

  • 1
    J
    class Solution:
        # @return an integer
        def reverse(self, x):
            if x < 0:
                s = str(0-x)
                s = s[::-1]
                x = 0-int(s)
            else:
                s = str(x)[::-1]
                x = int(s)
            if x > math.pow(2,31) or x < -math.pow(2,31):
                x = 0
            return x
    

    runtime: 74ms


  • 0
    B

    I am told that in Python less statements almost always means better performance.
    Take a look at this solution. I tried several times, the best one is 67 ms

    class Solution:
        # @return an integer
        def reverse(self, x):
            ret, i, s = 0, abs(x), -1 if x < 0 else 1
            while i:
                i, ret = i//10, ret * 10+ i%10
            return 0 if ret > pow(2, 31) else ret * s
    

Log in to reply
 

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