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.

思路:這道題從題意可知,不能使用額外空間。如果將數字逆序可能會超出int的內存。然後我就舉了一個例子,例如1234321,如何獲得最高位的1?

設f[0]=1,f[1]=10,f[2]=10^2,..f[n]=10^n,則最高位的1=1234321/f[6],次高位的2=(1234321-1*f[6])/f[5];最低位的1=1234321%f[1]/f[0],

次低位的2=(1234321-1*f[0])%f[2]/f[1],總結以上的推導,獲得的高位第i位公式爲leftNum = num/f[i],獲得低位的第i位公式爲

rightNum=num%f[i]/f[i-1]。故代碼如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        long long f[11];
        f[0] = 1;
        int i;
        for(i=1; i<=11; ++i)
        {
            f[i] = f[i-1] * 10;
        }    
        int n = 11;
        while(n > 0 && x/f[n] == 0)
        {
            n--;
        }    
        n++;    
        int left = x, right = x;
        int leftNum,rightNum;
        for(i=1; i<=n/2; ++i)
        {
            leftNum = left / f[n-i];
            left -= leftNum * f[n-i];
            rightNum = right % f[i] / f[i-1];
            right -= rightNum*f[i-1];
            if (leftNum != rightNum)
            {
                return false;
            }    
        }    
        return true;
    }
};


發佈了92 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章