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.
解:只需要将整数翻转一半即可,判断。
代码:
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0 || (x != 0 && x % 10 == 0))
return false;
int y = 0;
while(y < x){
y = y * 10 + x % 10;
x /= 10;
}
return (y == x)||(y/10 == x);
}
};
本文介绍了一种不使用额外空间判断整数是否为回文数的方法。通过将整数的一半进行反转并与另一半比较来实现,同时讨论了负数、溢出等特殊情况的处理。

被折叠的 条评论
为什么被折叠?



