7. Reverse Integer
7. Reverse Integer
Description:
题解:
solution 1:
一般思路:对于目标x,先判断x的正负,记录符号信息,然后对x做求余10获得尾数和整除10获得高位的操作,将获得的中间值进行累加得到最终的结果,然后在根据正负号输出最终的结果。(注意,需要进行越界处理)
Python3
class Solution:
def reverse(self,x):
"""
:type x: int
:rtype: int
"""
cnt = 0
a = 0
if x<0:
x = abs(x)
else:
cnt = 1
while x/10 > 0:
a = int(x%10) + a * 10
x = int(x/10)
if a > 2**31 and cnt==0:
return 0
if a >= 2**31 and cnt ==1:
return 0
if cnt == 0:
return a*-1
else:
return a
solution 2:
将逆序看成是字符串的逆序问题,所以算法的思路为,先判断正负,然后取绝对值,转为string,采用string的逆序函数,最终再转为整型添加正负号即可,中间同时需要进行范围溢出的判断。
class Solution:
def reverse(self,x):
s = 0
if x < 0:
s = -1
elif x==0:
s = 0
else:
s = 1
r = int(str(s*x)[::-1])
return s*r*(r < 2**31)