[LeetCode] Palindrome Number [13]

題目

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.

原題鏈接(點我)

解題思路

判斷一個int型整數是不是迴文數字,這個題也不難,依次取得數字最高位和最低位進行比較,就可以判斷是不是迴文數字。需要注意的是負數不是迴文數字。

代碼實現

代碼一

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        int times = 1;
        int p = x;
        while(p>=10){
            p /= 10;
            times *= 10;
        }
        int low = 0, high = 0;
        while(x!=0){
            low = x%10;
            high = x/times;
            if(low != high) return false;
            x = x%times;
            x /= 10;
            times /= 100;
        }
        return true;
    }
};

代碼二

思路相同,不同算法,明顯代碼一要簡潔很多

class Solution {
public:
    bool isPalindrome(int x) {
        if(x==0x80000000 || x<0) return false;
        if(x<0) x= -x;
        if(-9<=x && x<=9)
            return true;
        int n=0;
        int copy = x;
        while(copy != 0){
            ++n;
            copy /= 10;
        }
        copy = x;
        int i=n-1;
        while(i>=n/2){
            int h = nIndex(i);
            int high = x/h;
            int low = copy%10;
            if(high!=low) return false;
            x %= h;
            copy /= 10;
            --i;
        }
        return true;
    }
    int nIndex(int n){
        int temp =1;
        for(int i=0; i<n; i++)
            temp *= 10;
        return temp;
    }
};

-----------------------------------------------------------------------------------------------------------------------------------------
如果你覺得本篇對你有收穫,請幫頂。
另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.
你可以搜索公衆號:swalge 或者掃描下方二維碼關注我

(轉載文章請註明出處: http://blog.csdn.net/swagle/article/details/28913069 )

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章