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.

这个题其实就是判断一个数是否是对称的,原题中的hint提到的overflow是指如果一个数反转过来可能会溢出尴尬,会有人用这么笨的方法么,反转过来再判断是否相等???学渣都没想到这么渣的算法。。。。

好了,看到网上好多人用的都是一种方法,判断首位的数字是否相等,这个方法需要先计算这个数的最高位,用最笨的方法,乘10上去,最后除一下。。。然后在把这个数的首尾去掉,继续判断。。。。

说下我用的方法,就是用么。。

1 如果栈空,就把x%10入栈

2 栈不空,比较x%10和栈顶,不相等则入栈,相等则pop

3 如果该数为偶数,则用1,2即可,如果为基数,如101,则需要对最中间的数进行处理,我是先算出数的位数,然后当循环进行到中间时,直接再/10一次即可跳过对中间数的判断

4 栈为空返回true , 最后388ms过的

代码如下:

class Solution {

public:

    bool isPalindrome(int x) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        if(x<0) return false;
        if(x>=0&&x<10) return true;
        
        int n = log10(x) + 1;
        int i = 1;
        stack<int> s;
        //每次对x的余数进行考虑,用i记录是否到了中间
        for(; x!=0; x=x/10,i++){
            
            int current = x%10;
            if(s.empty()){
                //栈为空,则入栈
                s.push(current);
            }
            else {
                //栈不为空
                if(s.top()!=current){
                    //栈顶不等于余数,则入栈
                    s.push(current);
                }
                else{
                    //等于则出栈
                    s.pop();
                }
            }
            //下一次进行的就是中间数,直接/10跳过
            if(n%2!=0 && i==n/2){
                x=x/10;
            }
        }
        //栈不为空则返回true
        return s.empty()?true:false;
    }
};



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值