class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
negative = False
if(x < 0):
x = x * -1
negative = True
else:
x = x
sum = 0
dig = 1
strX = str(x)
lst = list(strX)
for i in lst:
sum += int(i) * dig
dig *= 10
if(abs(sum) > 2 ** 32):
return 0
elif(negative == True):
return sum * -1
else:
return sum
这是一个leetcode问题,要求我们反转一个整数。我知道这是一个脏代码,但它仍然可以工作,但当反向整数溢出时它不会返回0。我在电话里查过了if(abs(sum) > 2 ** 32):
return 0
但其中一个测试案例告诉我:Input: 1563847412Output: 2147483651Expected: 0
首先,我不知道为什么会溢出,也不知道如何修复。
谢谢!