LeetCode9:Palindromic Number

来源:互联网 发布:淘宝为什么搜不到斐讯 编辑:程序博客网 时间:2024/05/09 10:36

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;    }}