Palindrome Number--LeetCode

Palindrome Number

(原题链接: 点击打开链接)

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.

Solution:

判断回文数字,首先排除负数。然后根据回文的对称的特点我们可以从前后两端向中间一直判断是否对称。下面方法是先得到x的位数,然后根据求余整除得到每一位的数字,然后比较。时间复杂度为O(N)(N为x位数),可是设计大量的计算。
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return false;
        int i = 0;
        for(i; ;i++)
        {
            if(x / (int)pow(10,i) < 10) break;
        }
        i++; //i is the digital length of x
        cout<<i<<endl;
        for(int a = 0; a <= (i-1)/2; a++)
        {
            if(x % (int)pow(10, i - a) / (int)pow(10, i-a-1) != x % (int)pow(10, a + 1) / (int)pow(10, a)) return false;
        }
        return true;
    }
};

方法二:将数据进行翻转,由于翻转之后会造成溢出,所以将翻转后数据范围扩大
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return false;
        int y = x;
        long long int z = 0;
        int i = 0;
        while(y != 0)
        {
            z = z * 10 + y % 10;
            y = y / 10;
        }
        return x == z;
    }
};

方法三:对方法二进行优化。方法二对整个数进行了翻转,我们可以考虑只翻转这个数的后半部分然后和前半部分比较
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0 || (x != 0 && x % 10 == 0)) return false;
        int z = 0;
        while(x > z)
        {
            z = z * 10 + x % 10;
            x = x / 10;
        }
        return x == z || z / 10 == x;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值