Programming

Leetcode-9. Palindrome Number

Leetcode-9. Palindrome Number

Given an integer x, return true if x is a palindrome , and false otherwise.

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

<解題>String s = String.valueOf(x); // 將整數 x 轉換為對應的字串


class Solution {
    public boolean isPalindrome(int x) {
        String s = String.valueOf(x);  // 將整數 x 轉換為對應的字串
        int n = s.length(); 

        for (int i=0; i<n/2; i++) {
            if (s.charAt(i) != s.charAt(n-i-1)) return false;
            //從前面往後和後面往前算
        }

        return true;
    }
}

Time: O(N) Space: O(1)

<解題>String s = String.valueOf(x); // 將整數 x 轉換為對應的字串

只要 x 的數字還有一半以上未處理,就繼續迴圈。在迴圈中,我們將 x 的最後一位數字取出(x % 10),然後加到 rev 的末尾,即將 rev 左移一位(rev = rev * 10 + x % 10),同時將 x 的最後一位數字去掉(x = x / 10) *x 等於 rev 右移一位後的值,實際上是在處理奇數位數的回文數的情況,確保中間的數字不會影響判斷結果。 例如,考慮回文數 12321: 當 x 變成 12,rev 變成 123,我們比較 x 和 rev 會發現它們不相等,但我們實際上應該將 x 的最後一位數(1)忽略,因為它位於回文數的中間。


class Solution {
    public boolean isPalindrome(int x) {
        if (x<0 || (x!=0 && x%10==0)) return false;
        int rev = 0;
        while (x>rev){
            rev = rev*10 + x%10;
            x = x/10;
        }
        return (x==rev || x==rev/10);
    }
}

Time: O(log(x)) Space: O(1)