代码如下:
#!/usr/local/bin/python3
# 有符号整数反转
# 只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0
def RevNum(x):
if x < 0:
flag = -1
x = abs(x)
else:
flag = 1
s = str(x)
rev_s = s[::-1]
rev_n = int(rev_s)
if flag * rev_n > (2**31 - 1):
return 0
elif flag * rev_n < -2**31:
return 0
else:
return flag * rev_n
n = -120
print(RevNum(n))
运行结果为:
-21