Brute Force Java Solution

  • 0

    This Solution has huge redundancy in getDigit() calculation. But it's quite straightforward.

    public class Solution {
        static final int MAX_DIGIT = 10;
        public boolean isPalindrome(int x) {
            // negative integer is not palindrome
            if(x < 0) return false;
            int low = 0, high = MAX_DIGIT;
            // get highest digit
            while(x < Math.pow(10,high)) high--;
            // validate each digit pair
            while(low < high) if(getDigit(low++, x)!=getDigit(high--, x)) return false;
            return true;
        private int getDigit(int n, int x){
            // edge case, x doesn't have n digit
            if(Math.pow(10, n) > x) return -1;
            // edge case, n is max digit
            if(n==MAX_DIGIT && x >= n) return x/n;
            // general case
            return (x%(int)Math.pow(10,n+1) - x%(int)Math.pow(10,n))/(int)Math.pow(10,n);

Log in to reply

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