Thursday, April 24, 2014

Leetcode (Python): Reverse Integer

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

Solution:

Python does not have the overflowing problem as whenever an integer overflows it promotes it to long values, that have arbitrary precision

class Solution:
    # @return an integer
    def reverse(self, x):
        if x<0:
            return -1*self.reverse(-x)
        sol = 0
        while x != 0:
            sol = sol*10 + x % 10
            x = x // 10
        return int(sol)

No comments :

Post a Comment