美文网首页
Q7 Reverse Integer

Q7 Reverse Integer

作者: 牛奶芝麻 | 来源:发表于2018-02-28 16:30 被阅读3次

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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解题思路:

将整数转化为字符串,处理完后转化为整数

注意点:

原数字和转化后的数字都不能溢出

Python实现:
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        min = -2**31
        max = 2**31 - 1
        if  x < min or x > max or x == 0:  # 0 不用反转
            return 0
        if x > 0:
            rev = int(str(x)[::-1])  # [::-1]字符串反转
        else:
            rev = -int(str(x)[1:][::-1])
        if rev < min or rev > max:  # 反转后的数字溢出
            return 0
        return rev

a = 1023456789
b = Solution()
print(b.reverse(a))  # 转化后的数字溢出,返回0

相关文章

网友评论

      本文标题:Q7 Reverse Integer

      本文链接:https://www.haomeiwen.com/subject/noimzxtx.html