Java code beat 100% of java coders with 26ms run time.


  • 0
    M
    public class Solution {
        	public boolean isPalindrome(int x) {
            if(x<0)return false;
    		int intLength = Integer.toString(x).length() - 1;
    
    		while (intLength > 0) {
    			int mostDigit = (int) (x / Math.pow(10, intLength)), leastDigit = x - ((x / 10) * 10);
    			if (mostDigit != leastDigit)
    				return false;
    			x -= (mostDigit * Math.pow(10, intLength));
    			x /= 10;
    			intLength-=2;
    		}
    		return true;
    	}
    }
    

  • 0
    H

    @msief I tried running your program but never got even close to 26 ms. In fact run time was lesser than this program.
    You are looping only N/2 times if N is the length of x instead of my program looping N times. Integer.toString(x).length() may be the culprit as this could be O(N) depending on JVM implementation?

    public class Solution {
        public boolean isPalindrome(int x) {
            if(x > Integer.MAX_VALUE||x < 0) return false;
            int oppo=0;
            int y=x;
            while(y!=0){
                oppo=oppo*10+y%10;
                y/=10;
            }
            return oppo==x;
        }
    }
    

Log in to reply
 

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