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
网友评论