Reverse Integer

题目描述

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

解题方法

跟reverse bits一样,只不过这里是signed value, 每次module 10更快

注意点

  • sign
  • overflow的问题, 32位integer range -2147483648 to 2147483647

Solution

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if not x:
            return 0
        sign = 1
        if x < 0:
            sign = -1
        x = abs(x)

        result = 0
        while x:
            curNum = x % 10
            result = result * 10 + curNum
            x = x / 10

        result = sign * result
        if result > 2**31 - 1 or result < -1 * (2 ** 31):
            return 0
        else:
            return result

Reference