Java solution beats 99% with no extra space or overflow


  • 2

    This solution compares the least significant digit with the most significant digit just like you would do with a string, then get rid of those digits and repeat.
    Example:

    1. x = 3428243
    2. d = 1000000
    3. (x%10) = 3, also (x/d) = 3, so keep going
    4. (x/d)*d = 3000000
    5. x - 3000000 = 428243
    6. x/10 = 42824
    7. d/100 = 10000
      Repeat till x = 0 (true) or break if step 3 fails (false)
    public boolean isPalindrome(int x) {
            if(x<0) return false;
            int d = 1;
            while(x/d>=10) d*=10;
            while(x>0){
                if(x%10 != x/d) return false;
                x = (x-(x/d)*d)/10;
                d/=100;
            }
            return true;
        }
    

Log in to reply
 

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