题目:
判断数字x是否为回文
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?
思路:
x<0 false
0<=X<10 true
9<x
判断数字x是否为回文
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?
思路:
x<0 false
0<=X<10 true
9<x
翻转(溢出,存在溢出的情况一定不为回文)
bool isPalindrome(int x)
{
if(x<0)
{
return false;
}
else if(x<10)
{
return true;
}
else
{
int temp=x;
int reverse=0;
while(temp>0)
{
reverse=reverse*10+(temp-(temp/10)*10);
temp=temp/10;
}
return reverse==x;
}
}
本文介绍了一种判断整数是否为回文数的方法,通过翻转整数并比较原数来实现,同时考虑了负数和溢出的问题。

280

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



