O(n) Simple Java Solution Without Extra Space & Without Reversing The Given Integer, where n = total no. of digits


  • 0
    J

    If a number is palindrome then the sequence of digits while checking the digits of the number in forward order should match the sequence while checking the digits in backward (reverse) order.

    class Solution {
        public boolean isPalindrome(int x) {
            if (x < 0) {
                return false;
            }
            int a = x;
            int b = x;
            int count = noOfDigits(b);
            int divisor = (int)Math.pow(10, count - 1);
            
            while (a != 0 && b != 0) {
                int z = a % 10;
                a = a / 10;
                
                int y = b / divisor;
                b = b % divisor;
                divisor = divisor / 10;
                
                if (z != y) {
                    return false;
                }
            }
            return true;
        }
        
        private int noOfDigits(int x) {
            int count = 0;
            while (x != 0) {
                x = x / 10;
                count++;
            }
            return count;
        }
    }
    

Log in to reply
 

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