python判斷迴文數的兩種方法--字符串和數字

1.轉字符串

class Solution:
    def isPalindrome(self, x: int) -> bool:
        x = str(x)
        lenth = len(x)
        for i in range(0,lenth//2):
            if x[i] != x[lenth-i-1]:
                return False
        return True

2.數字

class Solution:
    def isPalindrome(self, x: int) -> bool:
       if x<0:
           return False
       ls = []
       while x:
            i = x % 10
            x = x //10
            ls.append(i)
       lenth = len(ls)
       for i in range(0, lenth // 2):
            if ls[i] != ls[lenth - i - 1]:
                return False
       return True
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章