此篇文章為我的解題紀錄,程式碼或許並不是很完善

Leetcode - 9. Palindrome Number

解題思路

x轉為字串後再跑迴圈檢查是否為回文

我滴程式碼

1
2
3
4
5
6
7
8
9
class Solution:
def isPalindrome(self, x: int) -> bool:
word = str(x)
limit = int(len(word)/2)
size = len(word)
for i in range(limit):
if (word[i] != word[size - i - 1]):
return False
return True

看過大神後的程式碼

將字串翻轉後再檢查兩個字串是否相等

1
2
3
4
5
6
7
class Solution:
def isPalindrome(self, x: int) -> bool:
word = str(x)
txt = word[::-1]
if word == txt:
return True
return False