[LeetCode] Palindrome Number

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.

class Solution {
public:
    bool isPalindrome(int x) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(x < 0) return false;
        if(x < 10) return true;
        int base = 1, len = log(x) / log(10) + 1;
        for(int i = 1;i < len;i++) base *= 10;
        int s = 0, e = 0;
        while(len > 1)
        {
            s = x / base;
            e = x % 10;
            if(s != e) return false;
            else {len -= 2; base /= 100; x = (x % 10) / 10;}
        }
        return true;
    }
};
原文地址:https://www.cnblogs.com/changchengxiao/p/3470347.html