LeetCode7:Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


LeetCode:链接

灵感来源:LeetCode202:Happy Number

循环通过对10取模得到尾部数字,一步步乘10构造新的翻转后的整数即可。然而要注意首先判断原数字的正负,最后还要判断结果是否溢出。

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        # 先判断正负
        flag = 1 if x >= 0 else -1 
        x = abs(x)
        res = 0
        while x:
            cur = x % 10
            res  = res * 10 + cur
            x = x // 10
        res = flag * res
        return res if res < 2147483648 and res >= -2147483648 else 0

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84871843
今日推荐