5 Lines Python AC Solution Beats 100%


  • 1

    Simply reverse the decimal digits one by one.
    Hardcode 32-bit limitation to meet overflow requirement.

    class Solution(object):
        def reverse(self, x):
            res, remains = 0, abs(x)
    
            while remains:
                res, remains = res*10+remains%10, remains//10      # Updated thanks to Pythonaaron
    
            if x < 0: res *= -1
    
            return res if abs(res) < 0x7fffffff else 0
    

  • 0
    P

    inside the while loop,
    res, remains = res*10+remains%10, remains // 10


  • 0

    @Pythonaaron Thanks for your correction! Since the OJ is using Python 2.7, I've found a useful article clarifying the difference between / and //:

    In Python 3.0, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

    In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from future import division, which causes Python 2.x to adopt the behavior of 3.0


Log in to reply
 

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