[LeetCode]68. 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.

Subscribe to see which companies asked this question

解法1:首先想到的就是将整数转换为字符串,然后从两头往中间对比即可。或者将每一位分别取出来后暂存再前后比较。但是这样都需要额外的空间。

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        string s = to_string(x);
        int i = 0, j = s.size() - 1;
        while (i < j)
            if (s[i++] != s[j--]) return false;
        return true;
    }
};

解法2:可以想办法每次都取出整数的最高位和最低位进行比较,然后去掉这个最高位和最低位,取新的整数的最低位和最高位比较……

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        int num = x, n = 0;
        while (num > 0) {
            ++n;
            num /= 10;
        }
        if (n == 1) return true;
        int i = 1, j = n - 1;
        while (i <= j) {
            int low = x % (int)pow(10, i) / (int)pow(10, i - 1);
            int high = x / (int)pow(10, j) % 10;
            if (low != high) return false;
            ++i;
            --j;
        }
        return true;
    }
};

一种更简单的写法,严格按照上述思路:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        int n = 1;
        while (x / n >= 10) n *= 10;
        while (x > 0) {
            int low = x % 10;
            int high = x / n;
            if (low != high) return false;
            x = (x % n) / 10; //取出中间剩余的数字
            n /= 100; //注意每次去掉两位,因此除数相应缩小100倍
        }
        return true;
    }
};
原文地址:https://www.cnblogs.com/aprilcheny/p/4949712.html