给你一个 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:
str1 = str(x)
str2 = []
n = len(str1)
if x > 0:
for i in range(n):
str2.append(str1[n-i-1])
elif x == 0:
return x
else:
str2.append("-")
for i in range(n-1):
str2.append(str1[n-i-1])
res = int("".join(str2))
if res >= -2**31 and res <= 2**31-1:
return res
else:
return 0
官方解1
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] # 不包括字符串的0索引
x = int(str_x)
x = -x
return x if -2147483648 < x < 2147483647 else 0
官方解2
class Solution:
def reverse(self, x: int) -> int:
y, res = abs(x), 0
boundry = (1<<31) -1 if x>0 else 1<<31 # 1<<31 = 2147483648
while y != 0:
res = res*10 +y%10
if res > boundry :
return 0
y //=10
return res if x >0 else -res
官方解写的还是精妙许多