classSolution: defreverse(self, x: int) -> int: if -10<x<10: return x str_x = str(x)
if str_x[0] != "-": str_x = str_x[::-1] x = int(str_x) else: str_x = str_x[:0:-1] x = int(str_x) x = -x
return x if -(2**31)<x<((2**31) -1) else0
思路2:将x的值不断模10,得到的数字加到res中实现反转
1 2 3 4 5 6 7 8 9 10 11
classSolution: defreverse(self, x: int) -> int: y, res = abs(x), 0 # 则其数值范围为 [−2^31, 2^31 − 1] boundry = (1<<31) -1if x>0else1<<31 while y != 0: res = res*10 +y%10 if res > boundry : return0 y //=10 return res if x >0else -res