Leetcode 刷题:
一个easy级别的题目。
-
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 0 when the reversed integer overflows.
- 容易出现溢出问题。分享一个答案。
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x <2**31-1 and x>-2**31:
if x>0:
a = str(x)[::-1]
if int(a)<2**31-1:
return int(a)
else: return 0
elif x==0:
return 0
else:
b = str(-x)[::-1]
if -int(b)>-2**31:
return -int(b)
else: return 0
else:
return 0
运行效果如下: