Accepted JAVA solution, none-recursion, No extra space


  • 0
    J

    This solution doesn't reverse the original integer, so we don't have to worry about the Integer.MAX_VALUE that was pointed out in the hint.

        if (x<0) return false;        
    
        int length = String.valueOf(x).length();
        
        while(length>0){
            int right = (int) (x/(Math.pow(10,(length-1))));
            int left = x%10;
            if( right != left) return false;
            x = (int) (x%Math.pow(10,(length-1))); //remove the left most digit
            x = x/10; //remove the right most digit
            length = length - 2;
        }
        return true;
    

    It can also be written as following to avoid multiple computation of Pow(), but it's less intuitive:

        if (x<0) return false;        
    
        int length = String.valueOf(x).length();
        int div = (int) (Math.pow(10,(length-1)));
    
        while(div>0){
            int right = x/div;
            int left = x%10;
            if( right != left) return false;
            x = (x%div); //remove the left most bit
            x = x/10; //remove the right most bit
            div /= 100;
        }
        return true;

  • 0
    J
    This post is deleted!

  • 0
    R

    “int length = String.valueOf(x).length(); ”: Will converting the Integer to String lead to the extra space? But this solution will not cause overflow


Log in to reply
 

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