9 palindrome number

这道题我之前有印象了,就是通过reverse integer的思路来判断

其实吧,可以触类旁通,凡事判断整个输入是不是palindrome的题,都可以用reverse的思路来做,如同 link list


public class Solution {
    public boolean isPalindrome(int x) {
/*        if(x==0) return true;
        else if(x<0) return false;
        else{
            int len=getLen(x);
            for(int i=1; i<=len/2; i++){
                if(getDigit(x, i)!=getDigit(x, len+1-i)) return false;  // I changed int len=getLen(x)/2, but did not change he getDigit(x, len+1-i), and spent some time debugging. Lesson learned: changing one thing could affect all the places using the previous statement. so not just searching locally, but globally. Or just keep it the previous way
            }
            // reaching to the middle, still no false, then it got to be true
            return true;
        }
    }
    
    public int getDigit(int x, int pos){
        return (x/(int)Math.pow(10,(pos-1)))%10;  // here why (int)??? double has different range than int
    }
            
    public int getLen(int x){
        int len=0;
        while(x!=0){
            len++;
            x/=10;  // typo, I wrote: len/=10; you silly!
        }
        return len;
    }
    // this is too slow, since iterate more than once, getLen iterate, and then compare iterate, can you iterate just once?*/
    
    // the above was written in beginning of Jan.17.
    // 看了一个极为简单的reverse int的做法来处理这个问题,太巧妙了!!重现一下。。。1.29.17
        if(x==0) return true;
        if(x<0 || x%10==0) return false;  // !!! 特殊情况就是 后面是有一串0的数。。。但是0就是true的,所以要提前判断。。这个很关键
        int reverseHalf=0;
        while(x>reverseHalf){
            reverseHalf=10*reverseHalf + x%10;
            x=x/10;
        }
        return (x==reverseHalf || x== reverseHalf/10);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值