Fastest Python solution


  • 0
    O

    The result appears to be the fastest Python solution on OJ, so I'm posting this here to hopefully help some people.

    class Solution:
        # @return an integer
        def reverse(self, x):
            final = ''
            y = str(x)
            for i in range(len(y)-1,-1,-1):
                if y[i].isdigit():
                    final = final + y[i]
                else:
                    final = y[i] + final
            if len(final) > 0:
                result = int(final)
            else:
                result = 0
            if math.fabs(result) > math.pow(2,31)-1:
                result = 0
            return result

  • 0
    K

    This one takes less time:

    class Solution:
        # @return an integer
        def reverse(self, x):
            f = x > 0
            if not f:
                x *= -1
    
            r = int(''.join(reversed(list(str(x)))))
    
            if r > 2147483647:
                return 0
    
            if not f:
                r *= -1
    
            return r
    

Log in to reply
 

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