Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
另一种方式是计算出最高位数,两个指针来比较left和right。
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.
分析:可以采用10进制的翻转,不断计算最小位的方式来乘除最后结果,判断最后结果与原来x是否相等。但是溢出的判断不好解决,虽然代码能通过。
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) return false;
int rx = 0;
int sum = x;
while(sum) {
int digit = sum % 10;
rx = rx * 10 +digit;
sum = sum / 10;
}
if(x == rx)
return true;
else
return false;
}
};
另一种方式是计算出最高位数,两个指针来比较left和right。
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) return false;
int base = 1;
while(x / base >= 10) {
base = base * 10;
}
while(x) {
int left = x / base;
int right = x % 10;
if(left != right) return false;
x -= left * base;
x /= 10;
base /= 100;
}
return true;
}
};