leetcode--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.

题目解题思路:

所谓回文数呢,就是将其reverse之后和之前的值是一样的。但是负数都不是回文数!!!有两种解题思路

1)之前写过的一篇将数reverse的函数,可以直接调用之前的那个函数,当然溢出情况在之前那个题目已经考虑了(其实我也不太确定这儿的溢出是不是指的就是前一题reverse的溢出??)

源代码如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0)
           return false;
        if(x < 10)
           return true;
        return reverse(x) == x ? true:false;
}
private:
    int reverse(int y)
    {
        int num = 0;
        int result = 0;
        while(y != 0)
        {
            num = y%10;
            if(result > INT_MAX/10)//之前将INT_MAX错写成了INT_MIN然后一直卡在11上面,捂脸~
              return 0;
            if(result == INT_MAX/10 && num > 7)
              return 0;
            result = result*10 + num;
            y = y/10;
        }
        return result;
    }
};

2)一次取头和尾比较,一直比较到结束或者不相同。那么问题又来了:怎么取头和尾呢?如果要是字符串到是好办,但是这儿不是字符串呀!

但是可以通过对这个数除10取余得最后一个数,可以通过对这个数除以10^length-1次幂取商得到首位,如12321,可以除以10取余得到最后一位1,除以10000取商得首位!!!

源代码如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0)
           return false;
        if(x < 10)
           return true;
        int length = 1;
        while(x / length >= 10)//求出长度
        {
            length *=10;
        }
        
        while(x != 0)
        {
            int left = x/length;
            int right = x % 10;
            if(left != right)
               return false;
            x = (x % length)/10;//先除以length取余得除第一位之外的剩余位;再对剩余位除10取商得除了最后一位的其余位
            length /=100;//每次长度减少两位
        }
        return true;
    }
};

Notice:在数学上的除以某个数取余得到后面位和除以某个数取商得到前面位,要熟悉呀要熟悉。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值