Java O(logn) 98% efficiency


  • 0
    U

    Here, we find the number power which is 10^(numDigits-1). Use two iterators one from the end one from the beginning of the number.

        public boolean isPalindrome(int x) {
            if (x < 0) return false; 
            int power = 1; 
            for (int n = x; (n/10) > 0; n /= 10, power *= 10) {   ;  }
            
            for (int n = 1; n < power; power /= 10, n *= 10) {
                if ( ((x/power) % 10) !=  ((x/n) % 10) ) return false;  
            }
            return true; 
        }
    

Log in to reply
 

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