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.

判断一个整数是否是回文数,要求是不使用额外空间。

回文数是指正着过去和反着回来都是一样的,如1221,12121.

本来可以转成字符串,然后从前后开始比较即可,但是题目说不能使用额外空间,所以这一条不成立。

可以旋转这个整数,旋转回来的数和这个数相等就是回文数。考虑到旋转会导致溢出,这时返回false即可,因为x是int型,如果是回文数,它也是x,不可能溢出。

还可以简洁一点,因为是前半部分和后半部分的旋转是一样的,所以可以旋转一半,这时比较。当然,这时要注意x由奇数个数字组成时和偶数个数字组成的情况,

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0||(x!=0&&x%10==0))
            return false;
        int res=0;
     /*
    //全部旋转
int a=x; while(x>0){ int tail=x%10; int newRes=res*10+tail; if((newRes-tail)/10!=res) return false; res=newRes; x=x/10; } return a==res; */ //旋转整数,只要旋转一半就行了,旋转一半就不会出现溢出问题 while(x>res){ res=res*10+x%10; x=x/10; } return x==res||res/10==x; //分别考虑x是偶数个数字组成,和x是奇数个数字组成 } }
原文地址:https://www.cnblogs.com/xiaolovewei/p/8058302.html