iT邦幫忙

0

解LeetCode的學習筆記Day9_Palindrome Number

LFI 2025-09-30 21:07:43124 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄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

圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言