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) {
int src = x;
int dst = 0;
int tmp;
while(src > 0)
{
tmp = src % 10;
dst *= 10;
dst += tmp;
src /= 10;
}
return x == dst;
}
};
本文介绍了一种不使用额外空间判断整数是否为回文数的方法。通过逆序比较原整数与逆序后的整数来实现,同时讨论了负数、整数溢出等特殊情况的处理。
372

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



