O(1) space Java solution without partial reversing

  • 0

    Hi guys!

    The approach is to find at first the largest power of ten less than x. And then we could iteratively compare a first digit with a last one cutting them in case of success for the next iteration.

    Actually, i don't agree that negative numbers can't be palindromes. To work the code for the case of negatives we could actually remove the check at the beginning and be fine.

    Hope it helps!

    public class Solution {
        public boolean isPalindrome(int x) {
            if (x < 0) return false;
            int d = 1;
            while (x/10/d != 0) d*=10; // find max power of ten less than x
            while (x != 0) {
                if (x/d != x%10) return false; // compare first and last digit
                x = (x%d)/10; // cut digits from both sides
                d /= 100; /* update max power of ten less than x */
            return true;

Log in to reply

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