Palindrome Number判断回文数

来源:互联网 发布:淘宝店怎样设置客服 编辑:程序博客网 时间:2024/05/22 04:50

题目:https://leetcode.com/problems/palindrome-number/description/

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

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.

题目大意:

即不适用额外空间验证一个数是否是回文数。


解法:

把这个数的头尾取出,并判断头尾两个数是否相等。

/**验证一个数是否是回文数  * @param x 需要验证的数 * @return验证结果 */public static boolean isPalindrome(int x) {if(x<0){return false;}int div=1;//取左右数进行对比//获取最大除数while (x/div>=10) {div*=10;}while(x>0){int left=x/div;int right=x%10;if(left!=right){return false;}x=(x-left*div)/10;div/=100;}return true;}