DEV Community

Cover image for 🔁 9-Palindrome Number || Efficient Half-Reversal || Runtime 3 ms (beats 98.66%) · Memory 63.98 MB (beats 78.96%) 🏆
Muhammad Zeeshan
Muhammad Zeeshan

Posted on

🔁 9-Palindrome Number || Efficient Half-Reversal || Runtime 3 ms (beats 98.66%) · Memory 63.98 MB (beats 78.96%) 🏆

🔗 Related Links

LeetCode Submission Results

Metric Value Percentile
Runtime 3 ms 98.66%
Memory 63.98 MB 78.96%

Explanation of Key Points

Early exits

  • Any negative number is not a palindrome (e.g., -121false).
  • Any number ending in 0 can’t be a palindrome unless it’s 0 itself (e.g., 10false).

Reversing half the number

  • Iteratively remove the last digit from x and append it to reverted.
  • Continue until the remaining part (x) is less than or equal to the reversed half (reverted), meaning we've processed at least half of the digits.

Handling odd/even length

  • Even length: The two halves must match exactly (x === reverted).
  • Odd length: The reversed half contains the middle digit, so drop it with Math.floor(reverted / 10) before comparing.

This approach satisfies LeetCode’s constraints (−2³¹ ≤ x ≤ 2³¹−1) and avoids any string conversions.


Complexity Analysis

  • Time Complexity:

    The loop processes roughly half of the digits of x. If x has d digits, it runs ~d/2 times → $$O(d) = O(\log_{10} x)$$.

  • Space Complexity:

    Only a constant number of integer variables are used → $$O(1)$$.


Code


javascript
/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    // Negative numbers or numbers ending with 0 (but not 0 itself) cannot be palindrome.
    if (x < 0 || (x % 10 === 0 && x !== 0)) {
        return false;
    }
    let reverted = 0;
    // Reverse digits until the original number is <= reverted reversed half
    while (x > reverted) {
        reverted = reverted * 10 + (x % 10);
        x = Math.floor(x / 10);
    }
    // For even length: x === reverted
    // For odd length: x === Math.floor(reverted / 10)
    return x === reverted || x === Math.floor(reverted / 10);
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)