整数反转

整数反转

1、题目

image-20231218101425194

2、题解

思路1:直接将int类型转换成str类型进行反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def reverse(self, x: int) -> int:
if -10<x<10:
return x
str_x = str(x)

if str_x[0] != "-":
str_x = str_x[::-1]
x = int(str_x)
else:
str_x = str_x[:0:-1]
x = int(str_x)
x = -x

return x if -(2**31)<x<((2**31) -1) else 0

思路2:将x的值不断模10,得到的数字加到res中实现反转

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def reverse(self, x: int) -> int:
y, res = abs(x), 0
# 则其数值范围为 [−2^31, 2^31 − 1]
boundry = (1<<31) -1 if x>0 else 1<<31
while y != 0:
res = res*10 +y%10
if res > boundry :
return 0
y //=10
return res if x >0 else -res

整数反转
http://example.com/2023/12/18/整数反转/
作者
Z Z
发布于
2023年12月18日
许可协议