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.

题意:判断一个数是不是回文数,注意负数不是回文数。题上要求空间复杂度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)是位数为奇数的回文数的情况
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值