Palindrome Number--LeetCode

Palindrome Number

(原題鏈接:點擊打開鏈接)

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.

Solution:

判斷迴文數字,首先排除負數。然後根據迴文的對稱的特點我們可以從前後兩端向中間一直判斷是否對稱。下面方法是先得到x的位數,然後根據求餘整除得到每一位的數字,然後比較。時間複雜度爲O(N)(N爲x位數),可是設計大量的計算。
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return false;
        int i = 0;
        for(i; ;i++)
        {
            if(x / (int)pow(10,i) < 10) break;
        }
        i++; //i is the digital length of x
        cout<<i<<endl;
        for(int a = 0; a <= (i-1)/2; a++)
        {
            if(x % (int)pow(10, i - a) / (int)pow(10, i-a-1) != x % (int)pow(10, a + 1) / (int)pow(10, a)) return false;
        }
        return true;
    }
};

方法二:將數據進行翻轉,由於翻轉之後會造成溢出,所以將翻轉後數據範圍擴大
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return false;
        int y = x;
        long long int z = 0;
        int i = 0;
        while(y != 0)
        {
            z = z * 10 + y % 10;
            y = y / 10;
        }
        return x == z;
    }
};

方法三:對方法二進行優化。方法二對整個數進行了翻轉,我們可以考慮只翻轉這個數的後半部分然後和前半部分比較
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0 || (x != 0 && x % 10 == 0)) return false;
        int z = 0;
        while(x > z)
        {
            z = z * 10 + x % 10;
            x = x / 10;
        }
        return x == z || z / 10 == x;
    }
};


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