Python3_Leetcode #9 回文数题解
思路:
1. 数字倒序比较法(基于LeetCode#8 数字反转来完成)
a. 将输入数字通过%10 求余 取反转
b.反转后数字与原来输入比较,一致则返回true
python3:
def isPalindrome(self, x: int) -> bool:
if x < 0 : #一开始加了x%10 == 0 这个判断,但是这样如果输入0 则会是错误的。所以去除
return False
reverse = 0
original = x
while x>0 :
x,pop = divmod(x,10)
reverse = reverse*10 + pop
if reverse == original :
return True
else:
return False
2. 字符串反转比较
思路和1类似,只不过通过字符串来进行反转。
def isPalindrome(self, x: int) -> bool:
if x < 0 :
return False
elif x == 0:
return True
else:
y = int(str(x)[::-1])
if x == y:
return True
else:
return False
----------------------------------------------
class Solution:
def isPalindrome(self, x: int) -> bool:return str(x)==str(x)[::-1]

浙公网安备 33010602011771号