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:链接
循环通过对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