9. Palindrome Number

来源:互联网 发布:mac os的硬件配置要求 编辑:程序博客网 时间:2024/06/05 20:50

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.

这道题最初的思路是找出数字的第一位数和最后一位数进行比较,直到所有位数都比较完成,即可判断出是否为回文数。后来看到了一个更加简单的方法:把数字的后半部分倒过来(即revertedNum),和前半部分(x)比较,对于偶数位的数字,若x == revertedNum, 则该数字为回文数;对于奇数位的数字,若x == revertedNum / 10, 则为回文数。

class Solution {public:    bool isPalindrome(int x) {        if (x < 0 || (x % 10 == 0 && x != 0))            return false;        int revertedNum = 0;        while (revertedNum < x) {            revertedNum = revertedNum * 10 + x % 10;            x /= 10;        }        return (revertedNum == x || revertedNum / 10 == x);    }};
原创粉丝点击