Java O(n) solution for reference, without overflow and extra space


  • 3
    Z

    Idea is simple, just compare the first an last digit each time.

    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        int divisor = 1;
        while( x/divisor >= 10) divisor *= 10;
        while(divisor >= 10 && (x / divisor == x % 10)){
        	x = (x%divisor)/10;
        	divisor /= 100;
        }
        return divisor >= 10 ? false : true;
    }

  • 0
    Q

    First,transfer the Integer to String.

    public boolean isPalindrome(int x){
    	if(x<0)
    		return false;
    	String s=Integer.toString(x);
    	int l=s.length();
    	for(int i=0;i<=(l/2);i++){
    		if(s.charAt(i)!=s.charAt(l-i-1)){
    			return false;
    		}
    	}
    	return true;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.