题目要求:
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.
题目解题思路:
所谓回文数呢,就是将其reverse之后和之前的值是一样的。但是负数都不是回文数!!!有两种解题思路
1)之前写过的一篇将数reverse的函数,可以直接调用之前的那个函数,当然溢出情况在之前那个题目已经考虑了(其实我也不太确定这儿的溢出是不是指的就是前一题reverse的溢出??)
源代码如下:
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
if(x < 10)
return true;
return reverse(x) == x ? true:false;
}
private:
int reverse(int y)
{
int num = 0;
int result = 0;
while(y != 0)
{
num = y%10;
if(result > INT_MAX/10)//之前将INT_MAX错写成了INT_MIN然后一直卡在11上面,捂脸~
return 0;
if(result == INT_MAX/10 && num > 7)
return 0;
result = result*10 + num;
y = y/10;
}
return result;
}
};
2)一次取头和尾比较,一直比较到结束或者不相同。那么问题又来了:怎么取头和尾呢?如果要是字符串到是好办,但是这儿不是字符串呀!
但是可以通过对这个数除10取余得最后一个数,可以通过对这个数除以10^length-1次幂取商得到首位,如12321,可以除以10取余得到最后一位1,除以10000取商得首位!!!
源代码如下:
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
if(x < 10)
return true;
int length = 1;
while(x / length >= 10)//求出长度
{
length *=10;
}
while(x != 0)
{
int left = x/length;
int right = x % 10;
if(left != right)
return false;
x = (x % length)/10;//先除以length取余得除第一位之外的剩余位;再对剩余位除10取商得除了最后一位的其余位
length /=100;//每次长度减少两位
}
return true;
}
};
Notice:在数学上的除以某个数取余得到后面位和除以某个数取商得到前面位,要熟悉呀要熟悉。