您的位置:首页 > 其它

Palindrome Number

2015-06-13 11:15 393 查看
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. 

方法一(不推荐):利用Reverse Integer的方法,求的转换后的数字,然后比较是否相等。提示说这样有溢出的问题,想了想感觉问题不大。因为首先输入必须是一个合法的int值,负数直接返回false,对于正数,假设输入的int是一个palindrome,reverse之后依然不会溢出,所以正常返回true;所以如果转换后溢出了,证明肯定不是palindrome,溢出后的数字跟输入一般不相同(想不出相等的情况-_-!,求指点),所以返回了false。 

方法二:从两头依次取数字比较,向中间推进。

C代码如下:

bool isPalindrome(int x) {
int i, j;
if(x < 0)
return 0;
else if(x < 10)
return 1;
int base = 1;
int save;
save = x;
for(i = 0; x / base >= 10 ; i++)
base *= 10;
for(j = 0; i >= j; j++)
{
if(save / base != x % 10)
return 0;
else
{
save %= base;
x /= 10;
base /= 10;
i--;
}
}
return 1;
}


小结:

(1)注意所有可能发生的变量溢出的情况,如果第一个for循环里的终止条件是x/base != 0,则x足够大时base可能溢出。

(2)如果需要一直用到10的次方这样的数,可以一开始就算出来并保存在变量里,而不必每次都调用pow()函数,减少计算量。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode