题目
给你一个 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
提示:
-231 <= x <= 231 - 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的题解
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
l=list(str(x))
if l[0]=='-':
negative=True
l=l[1:]
else:
negative=False
l1=[]
while len(l)!=0:
l1.append(l.pop())
if negative==True:
l1.insert(0,'-')
num=int(''.join(l1))
if (num<-2**31)|(num>2**31-1):
return 0
else:
return num
效率不咋高。
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x<0:
negative=True
s=str(x)[1:]
else:
negative=False
s=str(x)
rs=''
for i in range(len(s)-1,-1,-1):
rs+=s[i]
num=int(rs)
if negative==True:
num=-num
if (num<-2**31)|(num>2**31-1):
return 0
else:
return num
效率依然不咋高。
没办法,看答案了。。。
其他题解
1. 字符串反转
class Solution:
def reverse(self, x):
tmp = int((str(x) if x > 0 else str(-x) + "-")[::-1])
return tmp if -2 ** 31 < tmp < 2 ** 31 - 1 else 0
答主说自己性能打败了97%用户,我自己跑了一遍,跟我上面代码性能差不多。。。
2. 除余数
一个大神的C++题解,我用python写出来了。大神写的只适用于正数,我简单改了一下,更加符合提议。不得不说这个思路还是很强的。
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x<0:
negative=True
x=-x
else:
negative=False
n=0
while x!=0:
n=n*10+x%10
x=x//10
if negative==True:
n=-n
if -2**31<=n<=2**31-1:
return n
else:
return 0
官方题解是C++和java的,考虑到变量的溢出问题。但python没有这个问题。评论区有人说python的int就是long来储存的,不需要考虑溢出问题。
还有一个精选评论,思路类似。
def reverse_better(self,x):
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
逛了一圈评论区和题解,基本就是这两个思路。