[9] Palindrome Number

1. 題目描述

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.

檢查一個數字是否爲迴文。

2. 解題思路

翻轉一個整數,使用一個數字來暫存翻轉後的結果。翻轉的方式爲1234->4321 = (((4)*10+3)*10+2)*10+1,即使用前面的結果*10+最後一位的方式,使數字倒置。根據提示中所示,負數是不可能爲迴文的,因爲不會出現“-11-”這樣的數字。那麼還有一個情況需要考慮,就是如果一個整數超過2147483647再產生進位就變爲了一個負數不可能爲一個迴文了,加上這個判斷又超過了15%的代碼。

3. Code

public class Solution {
    public boolean isPalindrome(int x) {
        // 負數不可能成爲迴文
        if(x < 0) return false;
        int rev = 0;
        int cur = x;
        // 翻轉數字
        while(cur > 0)
        {
            rev = rev*10 + cur%10;
            // 正數越界,返回false
            if(rev < 0) return false;
            cur/=10;
        }
        if(rev != x) return false;
        return true;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章