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.
这道题,巨汗,提交了好几次才成功,我的基本思路就是在循环体中,不断地比较第i位和倒数第i位,直到遇到最中间的1个数字(输入为奇数个数字)或者遇到最中间的2个数字(输入为偶数个数字)时进行一些特殊的判断。需要注意的是,本题题目要求不能用额外的空间,所以无法借用之前的一道判断字符串是否为回文的题目的经验了。
这几个case造成了前几次的失败:
Input: 1001
Output: false
Expected: true
Input: 1000110001
Output: false
Expected: true
Input: 1020110201;
Output: false
Expected: true
修正后的最终代码如下:
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==INT_MIN)
return false;
if(x==0)
return true;
if(x<0)//测试得知,Online Judge应该是默认认为全部负数都return false。
return false;
while(x){
if((x<100)&&(x>10)&&(x%11==0))
return true;
if(x<10)
return true;
int count=0;
int large_digit=x;
int large_digit2=x;
while(large_digit2>=100){
large_digit2=large_digit2/10;
count++;
}
large_digit=large_digit2/10;
count++;
int small_digit=x-x/10*10;
int y=x/10;
int small_digit2=y-y/10*10;
// std::cout<<"large_digit2="<<large_digit2<<",small_digit2="<<small_digit2<<std::endl;
if(large_digit2%10==0&&small_digit2==0)
x = (x - (int)pow(10,count)*large_digit)/10+1*pow(10,count-2)+1;
else if(large_digit2==10&&small_digit2!=0)
return false;
else
x = (x - (int)pow(10,count)*large_digit)/10;
// std::cout<<"larget_digit="<<large_digit<<",small_digit="<<small_digit<<",new x="<<x<<std::endl;
if(small_digit!=large_digit)
return false;
}
return true;
}
};
总觉得自己啰啰嗦嗦写了一堆,看着实在不爽。看了一下leetcode.com上的参考答案,非常优美简洁。它使用一个表达位数的变量(div)来表达计算头部,使用%10来计算尾部。
bool isPalindrome(int x) {
if (x < 0) return false;
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
int l = x / div;
int r = x % 10;
if (l != r) return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}