Determine whether an integer is a palindrome. Do this without extra space.
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.
Solutions:
分别在取最高位和最低位的数字对比一下,不同则返回false。
例如对于 121,取最前面的1用121 / 100,取最末尾的1 用121%10,取完后121变为2,一次取两位,max也要一次少两位(max /= 100)。
易出错的地方是max循环开始前的值得确定,还有是while循环条件的确定。
有人直接用
int max=1;
while(max<=x/10) {
max*=10;
}
就确定了max的值
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) {
return false;
}
if(x<10) {
return true;
}
int max=10;
int t=x/10;
while(max<t) {
max *= 10;
}
//max /=10;
if(x/max >= 10) {
max *= 10;
}
int min=10;
while(max >= min) {
if(x/max != x%min){
return false;
}
x %= max;
x /= min;
max /= 100;
//min *= 10;
}
return true;
}
};