Java - Do not destroy x


  • 0
    M

    After getting a bit wrapped around the axle thinking I could not store the reversed int due to the 0 space constraint, I came up with this. It's a bit contrived but I think it's pretty cool and easy to understand, it can return as soon as it encounters a mismatch, and it doesn't destroy x!

    public boolean isPalindrome(int x) {
            if(x < 0) return false;
            int numberOfDigits = (int)Math.log10(x);
            for(int i = numberOfDigits; i >= numberOfDigits / 2; i--){
                int front = (x / (int)Math.pow(10, i)) % 10;
                int tail = (x / (int)Math.pow(10, numberOfDigits - i)) % 10;
                if(front != tail)return false;
            }
            return true;
        }
    

Log in to reply
 

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