LeetCode 第 9 题(Palindrome Number)

来源:互联网 发布:牛叉网络加速新域名 编辑:程序博客网 时间:2024/05/16 05:58

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;}
1 0
原创粉丝点击