LeetCode #9 - Palindrome Number - Easy

Problem

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

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.

Example

Input:-2147483648
Output:flase

Algorithm

整理一下題意:給定一個整數,判斷其是否是迴文數。要求不使用額外空間。

由於對空間使用有限制,所以要控制空間複雜度爲O(1)。於是很自然地想到利用迴文數的性質。迴文數的特點在於數字可以形成對稱,於是將這個數反過來還是和原來的數相等。於是只要開兩個變量來得到翻轉後的數字,再將翻轉後的數字與原數比較即可。

注意負數均不是迴文數。

代碼如下。

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

        int temp=x,reverse=0;
        while(temp){
            reverse=reverse*10+temp%10;
            temp/=10;
        }
        if(reverse==x)return true;
        else return false;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章