LEETCODE 02
7 整数反转
整数反转
解法一:字符串截取
a[开始截取位置:结束截取位置:步长] 包括开始截取位置字符,不包括结束截取位置字符。步长-1则代表反向截取。例如 a = [1, 2,
3, 4, 5, 6, 7] ,求a[1:5:-2],因为步长为-2,是负数,先对a反转,即[7, 6, 5, 4, 3, 2,
1],然后对反转后的列表从index=1(值为6)开始进行切片,结束位置index=5 (值为2), 步长为2,即[6, 4, 2]。
class Solution:
def reverse(self, x: int) -> int:
str_x=str(x)
if str_x[0]!='-':
res=int(str_x[::-1])
else:
temp=int(str_x[::-1][:-1])
res=-temp
return res if -2147483648 < res < 2147483647 else 0
解法二:
def reverse_better(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
9 回文数
class Solution:
def isPalindrome(self, x: int) -> bool:
y=abs(x)
res=0
if x<0:
return False
elif x==0:
return True
else:
while y!=0:
res=res*10+y%10
y//=10
return True if res==x else False
优化
class Solution:
def isPalindrome(self, x: int) -> bool:
###优化:
y,res=abs(x),0
if x<0 or (x/10==0 and x!=0):
return False
elif x==0:
return True
else:
while y!=0:
res=res*10+y%10
y//=10
return True if res==x else False