LeetCode#9* Palindrome Number

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Acmer_Sly/article/details/75213688

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.

题意:判断一个数是不是回文数,注意负数不是回文数。题上要求空间复杂度O(1)。
我的思路:将输入整数转换成倒序的一个整数,再比较转换前后的两个数是否相等。
代码:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0)return false;
        long int x1=x;      //用long int的原因是怕倒序之后超int
        long int rx=0;
        while(x1>0)
        {
            rx=rx*10+x1%10;
            x1=x1/10;
        }
        if(rx==x)return true;
        else return false;
    }
};

然后用时就相对比较多,然后我看了耗时较少的代码,它的思路就主要是在我的想法上面优化,就是前半段和后半段相比较,比如“1221”就比较“12”和“21”是否相等就行了,这样while循环就至少减少了一半。

class Solution {
public:
    bool isPalindrome(int x) {
        if ((x<0)||(x!=0&&x%10==0)) return false;
        int res=0;
        while (x>res) {
            res=res*10+x%10;
            x=x/10;
        }
        return res==x||res/10==x;  //(x==sum/10)是位数为奇数的回文数的情况
    }
};

猜你喜欢

转载自blog.csdn.net/Acmer_Sly/article/details/75213688