Given a 32-bit signed integer, you need to invert the digits on each of the integers.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assuming that our environment can only store 32-bit signed integers, the value range is [−231, 231 − 1]. According to this assumption, if the integer overflows after the inversion, it returns 0.
Source: LeetCode
class Solution:
def reverse(self, x: int) -> int:
# 先取 绝对值 再转化为字符串
s = str(abs(x))
# 取反
s = s[::-1]
if x < 0:
s = '-' + s
# 转化为整型
res = int(s)
if -2 ** 31 <= res <= 2 **31 - 1:
return res
else:
return 0