您的位置:首页 > 其它

LeetCode 第 9 题(Palindrome Number)

2016-04-18 13:19 246 查看

LeetCode 第 9 题(Palindrome Number)

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.

这道题很简单,可以利用第 7 题的部分代码。 第 7 题将一个整数的各个十进制位翻转了。如果翻转之后数字没有变化就说明是个 palindrome。

而且我们也不用考虑所谓的整数溢出问题,因为发生溢出的数肯定不是 palindrome。因此,就有了下面的代码。

bool isPalindrome(int x)
{
if(x < 0) return false;
int ret = 0, xx = x;
do
{
ret = 10 * ret + xx % 10;
xx = xx / 10;
}while(xx);
return ret == x;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: