题目:
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
代码:
class Solution:
def reverse(self, x: int) -> int:
#先将输入的有符号整数,转换成字符串形式
str_x=str(x)
#将得到的经过转换的字符串,转换为列表的形式,便于进行列表元素的翻转操作
list_x=list(str_x)
#将列表中的元素进行翻转
list_x.reverse()
#删除列表中位于非零元素前的所有零元素
for i in range(len(list_x)):
if list_x[i]==0:
continue
else:
list_x=list_x[i:]
break
#判断输入的有符号整数的正负
if list_x[-1]=='-':
#判断输入的有符号整数为负数时,在列表的第一位元素前插入负号,并删除位于列表最后一位的负号
list_x.insert(0,'-')
list_x=list_x[:-1]
#将列表中的所有元素,用‘‘连接为新的字符串’,然后将其转换为int形式
list_x=''.join(list_x)
list_x=int(list_x)
else:
#将列表中的所有元素,用‘‘连接为新的字符串’,然后将其转换为int形式
list_x1=''.join(list_x)
list_x=int(list_x1)
#判断经过转换得到的有符号整数是否在题目要求的范围内,若超出这个范围,则为溢出,则返回0值
if list_x>(-2**31) and list_x<(2**31-1):
return list_x
else:
return 0