Description:
Determine whether an integer is a palindrome. Do this without extra space.
Solution:
不用额外的空间判断回文数。
这个是我一开始的想法,把数字翻转过来,比较下和原来是否相等。
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return 0;
else if(x==0)
return 1;
long y=0;
int x0=x;
while(x>0)
{
y=y*10+(x%10);
x=x/10;
}
if(y==x0)
return 1;
else
return 0;
}
};
虽然AC了,但后来想一想根本用不着把数全翻过来,翻一半就好了。
还有可以一开始就把负数和10的倍数(除了0)排除掉。
改完如下:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0||(x%10==0&&x!=0))
return 0;
int y=0;
while(x>y)
{
y=y*10+(x%10);
x/=10;
}
if(x==y||x==(y/10))
return 1;
else
return 0;
}
};