1.题目描述
给你一个 32 位的有符号整数 x ,返回 x 中每位上的数字反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.思路
2.1推入法
将x从个位开始,逐个推到result中即可。不过需要注意对数值是否超出范围进行判断。
class Solution:
def reverse(self, x: int) -> int:
result = 0
while(x!=0):
result = result*10 + x%10
x = int(x/10)
if x<0:
x *= -1
if(abs(result) > 2**31):
result = 0
return result
2.2字符串法
先将x转化为字符串,然后反转,同样需要注意数值是否超出范围,还需要注意负数前的负号。
class Solution:
def reverse(self, x: int) -> int:
if x > 0:
result = int(str(x)[::-1])
else:
result = int((str(-x)+'-')[::-1])
if(abs(result) > 2**31):
result = 0
return result
这里用切片的方法完成逆序。