今天是紀錄LeetCode解題的第九天
是很簡單的一題題目
第九題題目:Given an integer x, return true if x is a palindrome, and false otherwise.
給定一個整數x,如果它是迴文回傳true,否則回傳false
把x轉成字串,直接比對原x和反轉後的x是否相同
class Solution:
def isPalindrome(self, x: int) -> bool:
str_x = str(x)
if str_x == str_x[::-1]:
return True
else:
return False
和第一種概念一樣,把切片寫法改成for迴圈,從最後面往回讀入儲存
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
l = []
for i in range(len(s)-1, -1, -1):
l.append(s[i])
r = ''.join(l)
if s == r:
return True
else:
return False
用取餘數的方式每次取得x(y)的最小位數的值儲存成n,最後比對n和x(y)是否相同
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
else:
y = x
n = 0
while y != 0:
n = n * 10 + y % 10
y = y // 10
if x == 0:
return True
elif n == x:
return True
else:
return False