[LeetCode] Palindrome Number [13]

题目

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.

原题链接(点我)

解题思路

判断一个int型整数是不是回文数字,这个题也不难,依次取得数字最高位和最低位进行比较,就可以判断是不是回文数字。需要注意的是负数不是回文数字。

代码实现
代码一

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        int times = 1;
        int p = x;
        while(p>=10){
            p /= 10;
            times *= 10;
        }
        int low = 0, high = 0;
        while(x!=0){
            low = x%10;
            high = x/times;
            if(low != high) return false;
            x = x%times;
            x /= 10;
            times /= 100;
        }
        return true;
    }
};

代码二

思路相同,不同算法,明显代码一要简洁很多

class Solution {
public:
    bool isPalindrome(int x) {
        if(x==0x80000000 || x<0) return false;
        if(x<0) x= -x;
        if(-9<=x && x<=9)
            return true;
        int n=0;
        int copy = x;
        while(copy != 0){
            ++n;
            copy /= 10;
        }
        copy = x;
        int i=n-1;
        while(i>=n/2){
            int h = nIndex(i);
            int high = x/h;
            int low = copy%10;
            if(high!=low) return false;
            x %= h;
            copy /= 10;
            --i;
        }
        return true;
    }
    int nIndex(int n){
        int temp =1;
        for(int i=0; i<n; i++)
            temp *= 10;
        return temp;
    }
};

-----------------------------------------------------------------------------------------------------------------------------------------

如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号: swalge  或者扫描下方二维码关注我

(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/28913069 )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值