Determinewhether an integer is a palindrome(回文). Do this without extra space.
Some hints:
Couldnegative integers be palindromes? (ie, -1)
If you arethinking of converting the integer to string, note the restriction of usingextra space.
You couldalso 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 amore generic way of solving this problem.
这是一道争议很多的题。
首先题目要求不能申请额外的空间。很多网友说声明int也需要额外空间,利用递归算法还需要用到stack,所以严格来讲,这道没法做。我们可以不严格的设定,不声明数组,字符串,矢量等数据类型。
其次,hints中提示要考虑负数。实际上这道题的测试用例中是不考虑负数的。所有的负数都不是回文数。
hints中提示用reverse的方法可能会造成溢出。怎样才会溢出?32位机器上最大的正整数是2147483647。如果对它reverse,然后用一个int类型的变量存储reverse后的结果就会溢出。那么用double类型存储就可以防止溢出。实际上测试用例也没有考虑到这一点,用int存储reverse的结果也不会溢出。
思路有两种
一是比较整数的首尾,然后砍去首尾,重复以上步骤。
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int divisor=10;
int digits=0;
int temp=x;
while(temp>0){
temp/=divisor;
digits++;
}
while(x>0){
int head=x/pow(10,digits-1);
int tail=x%10;
if(head!=tail)
return false;
x=x%(int)pow(10,digits-1);
x/=10;
digits-=2;
}
return true;
}
};
二是将整数reverse一遍然后和原来的数值进行比较
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
if(x==0)
return true;
double reverse=0;
int temp=x;
while(temp>0){
reverse=reverse*10+temp%10;
temp/=10;
}
return reverse==x;
}
};
所以这道题整体上讲,题目要求不够严谨,测试用例也不够全面。看看就好。
也可以看看国外的码农如何探讨这个问题http://articles.leetcode.com/palindrome-number