LeetCode9:Palindromic Number

Determine whether an integer is a palindrome. Do this without extra space.


public class Solution {
    public boolean isPalindrome(int x) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(x<0)
            return false;
        
        int base=1;
        while(x/base>=10){
    	    base*=10;
    	}
        
        while(x!=0){
            if(x/base != x%10)
                return false;
            x=x%base;
            x/=10;
            base/=100;
        }
        return true;
    }
}

###Recursive Solution###
public class Solution {


    private int globalX;
    
    // Forward:  curX=curX/10 until it hit 0
    // Backward: globalX=globalX/10
    
    // On the way back, least significant digit of curX and globalX
    // should always equal.
    public boolean isPalin(int curX){
        if(globalX<0) return false;
        if(curX==0) return true;
        
        if(isPalin(curX/10)
            && (curX%10==globalX%10) ){
            globalX/=10;    
            return true;
        }
        return false;
    }
    
    public boolean isPalindrome(int x) {
        globalX=x;
        return isPalin(x);
    }
}


My solution, compare from the middle to head/end:

public class Solution {
    public boolean isPalindrome(int x) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(x<0)
            return false;

        //get length: l+1
        int l = (int)(Math.log10(x));
        //odd
        if(l%2==0){
            int i = l/2;
            int pre,post;
            while(i>0){
                post = (int)(x/Math.pow(10,i-1))%10;
                pre = (int)(x/Math.pow(10,l-i+1))%10;
                if(pre!=post)
                    return false;    
                i--;
            }
            
        }
        //even
        else{
            int i = (int)Math.floor(l/2);
            int pre,post;
            while(i>=0){
                post = (int)(x/Math.pow(10,i))%10;
                pre = (int)(x/Math.pow(10,l-i))%10;
                if(pre!=post)
                    return false;    
                i--;
            }
        }
        return true;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值