目录
题目描述
输入/输出描述
解决方案
代码
代码走读
传送门
题目描述
给出一个32位的有符号整数,你需要将这个整数中每位上的数字反转。对于溢出32位的数字则返回0。
输入/输出描述
| 输入 | 321 |
| 输出 | 123 |
解决方案
题目较为简单,需要在两个地方注意:
- 输入的数字可能是负数。负数反转后还是负数
- 反转后的数字如果超出32位,则需要返回0
代码
class Solution:def reverse(self, x: int) -> int:positive = Trueif x < 0:positive = Falsex = -xx = int(str(x)[::-1])if not positive:x = -xif self.out_of_range(x):return 0else:return x@staticmethoddef out_of_range(x: int) -> bool:return x > 2 ** 31 - 1 or x < -2 ** 31
代码走读
class Solution:def reverse(self, x: int) -> int:# 先判断x正负性。记录后将x统一转换成正数(方便逆序)positive = Trueif x < 0:positive = Falsex = -x# 逆序,再根据之前的正负性记录还原xx = int(str(x)[::-1])if not positive:x = -x# 判断x是否溢出32位if self.out_of_range(x):return 0else:return x@staticmethoddef out_of_range(x: int) -> bool:return x > 2 ** 31 - 1 or x < -2 ** 31
传送门
LeetCode试题链接
str()函数
int()函数