Skip to content

LeetCode: 9-Palindrome Number 解題紀錄

Last Updated on 2021-01-06 by Clay


題目

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Follow up: Could you solve it without converting the integer to a string?

Example:

Input: x = 121
Output: true

Input: x = -121
Output: false

本題給定一範圍介於 -2^31-1 和 2^31 之間的整數值,然後我們必須判斷該數值是否顛倒過來也是相同的,有點像是數值本身的『回文』。

當然,這題將其數值轉成字串來解題是非常直覺的。不過在題目的 Follow up 中提到,是否能不轉為字串來解開這個題目呢?


解題思路

由於我在解這題之前,已經簡單看過 7. Reverse Integer 這題的解法,所以馬上想到了一個挺相似的解題方法。

  • 首先判斷數值是否為負值,若為負值則回傳 false負數一定不回文)
  • 建立個初始值為 0 的變數,用來儲存回文後的數值
  • 建立迴圈,每次都將輸入值 x 的個位數取出(% 10 即是),然後將數值整除 10(等於個位數不見了
  • 每次迴圈執行過程中,都先將回文值乘十,在加上 x 的個位數
  • 在 x 值最後一位取完後,即離開迴圈,比較原本的 x 值與回文值是否相同


C++ 程式碼

class Solution {
public:
    bool isPalindrome(int x) {
        // Preventation
        if (x < 0) return false;

        // Init
        long int x_reverse = 0;
        int x_origin = x;
        
        // Calculate reverse value
        while (x) {
            x_reverse = x_reverse*10 + x%10;
            x /= 10;
        }
        
        return x_origin == x_reverse;
    }
};


Python 程式碼

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0: return False
        x = str(x)
        return x == x[::-1]


順帶一提我 Python 一開始也是像我想像地那樣去解題 ...... 但意外地居然轉成字串解比較快。

我發現我就算學習 Python 到第三個年頭了,還是沒有很清楚 Python 的語言特性,著實慚愧。


References

Leave a Reply取消回覆

Exit mobile version