Java Solution by Indexing the integer


  • 0
    M

    This iterative solution has indexes to the right and left side of the integer and compares the digits at the left and right working toward the middle. If the integer at left is not equal to the integer at right return false;

    public class Solution {
        // 121 => true
        // 1221 => true
        // 1 => true
        // any x < 0 => false
       
        private int digit(int x, int i){
            // digit at index, 0-indexed
            // assert i >= 0;
            // assert i < length(x);
            // trim off all digits from 0 to i-1
            int quotient = (int) (x / Math.pow((double)10, (double)i));
            // return ith digit
            return quotient % 10;
        }
        private int length(int x){
            int length = 0;
            while(x != 0){
                x /= 10;
                length++;
            }
            return length;
        }
        public boolean isPalindrome(int x) {
            // This logic is very similar to the string version of solving the problem
            // The runtime is O(n) and the space complexity is O(1)
            
            // String sent = (new Integer(x)).toString();
            // int start =  0;
            // int end = sent.length()-1;
            // while(start < end){
            //     if (sent.charAt(start++) != sent.charAt(end--)){
            //       return false; 
            //     }
            // }
            // return true;
            
            if (x < 0) return false;
            int end  = length(x) - 1;
            int start = 0;
            while (start < end) {
                if (digit(x, start++) != digit(x, end--)){
                    return false;
                }
            }
            return true;
            
            
            
        }
    }

Log in to reply
 

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