15. Check Whether a Number Is a Palindrome

Difficulty:EasyPattern:Number ReversalTime:O(d)Space:O(1)

Determine whether a number reads the same from left to right and right to left.

How It Works & Algorithmic Design

A number is a palindrome if it equals its reversed form:

  1. Store the original number.
  2. Reverse the number using digit extraction.
  3. Compare the reversed number with the original.
  4. Return true when they are equal; otherwise return false.

Why This Approach Works Best

The number is processed digit by digit. The algorithm requires $O(d)$ time and $O(1)$ auxiliary space.

Example Walkthrough
Input: 1221
The digits are symmetric.
Reverse: 1221
Reversing the number produces the same value.
Output: true
Original and reversed values are equal.

Answer: Check numeric palindrome

function isPalindrome(n) {
  if (n < 0) return false;

  const original = n;
  let reversed = 0;

  while (n > 0) {
    reversed = reversed * 10 + (n % 10);
    n = Math.floor(n / 10);
  }

  return original === reversed;
}
💡 Reverse the number and compare it with the original value.
Key Takeaways
  • A numeric palindrome is equal to its reversed value.
  • Negative numbers are generally not considered numeric palindromes.
  • The solution takes O(d) time and O(1) space.