Simple Java solution pruning the first and last digits at each step


  • 0
    M

    Maybe there are some extra operations here but wanted to share this overflow safe approach

        public boolean isPalindrome(int x) {
            if (x<0) return false;
            int exp =1, y=x;
            while (y / 10 != 0){
                exp*=10;
                y/=10;
            }
            while(x!=0 || (x<-9 && x>9)) {
                int l = (x / exp), r = (x % 10);
                if (l != r) return false;
                x = (x % exp) / 10;
                exp = Math.max (1, exp / 100);
            }
            return true;
        }
    

Log in to reply
 

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