将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]
例子:
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
知识点:
- int会自动忽略前面的0
- str的切片: 字符串[开始索引:结束索引:步长]
- int 范围: [−231, 231 − 1]
code:
class Solution:
def reverse(self, x: int) -> int:
if x > 2**31-1 or x < -2**31:
return 0
else:
strx = str(x)
if x > 0:
result_str = strx[::-1]
else:
result_str = strx[0] + strx[:0:-1]
result = int(result_str)
if result > 2**31-1 or result < -2**31:
return 0
else:
return result