Easy python solution with join reverse


  • 1
    T
    class Solution(object):
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            r = 0
            if x < 0:
                x = abs(x)
                r = -int(''.join(list(str(x))[::-1]))
            else:
                r = int(''.join(list(str(x))[::-1]))
                
            if r < -2147483647 or r > 2147483647:
                return 0
            else:
                return r

  • 0

    Good code and is easy to understand.
    But if x < 0, why do you use x = abs(x) since you know x is below zero? I replace it by x=-1*x, and improve your code from 72 ms to 62 ms.


  • 0
    V

    can simplify int(''.join(list(str(x))[::-1])) to int(str(x)[::-1])


Log in to reply
 

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