LeetCode 9. Palindrome Number回文数判断
Description:
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.
分析:
首先,负数和以0结尾的数可以排除掉,直接返回FALSE;
然后,根据输入数据的左右部分是否相等,从而判断出回文数。
这里主要用到一个循环,利用求余数法,不断将余数×10,得到右边倒序过来的数据,直至该结果大于等于左边剩下的数。
最后,判断两边的数是否相等,若相等,则说明是回文数,返回TRUE;否则返回FALSE。
代码如下:
1 |
|