一、题目描述
给你一个 32 位的有符号整数 x
,返回将 x
中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1
输入:x = 123
输出:321
示例 2
输入:x = -123
输出:-321
示例 3
输入:x = 120
输出:21
示例 4
输入:x = 0
输出:0
二、代码
代码如下:
class Solution:
def reverse(self, x: int) -> int:
if x == 0 or x < -math.pow(2,31) or x >(math.pow(2,31)-1) :
return 0
else:
list = []
fuhao = ''
for e in str(x):
list.append(e)
if list[0] == '-':
fuhao = list.pop(0)
x_re = ''
list.reverse()
while list[0] == '0':
list.pop(0)
for i in range(len(list)):
x_re = x_re + list[i]
x_re = fuhao + x_re
if int(x_re) < (-math.pow(2,31)) or int(x_re) >(math.pow(2,31)-1):
return 0
else:
return int(x_re)
三、解题思路
PS:个人能力有限,不考虑时间空间最优。
本题思路简单,将拿到的int类型数字转换为list列表,再用list自带的反转方法reverse进行反转,最后再输出;
需要注意的是符号问题,如果带有负号的话,可以先提取负号出来,最后等反转后再加到字符串前面。