15. Check Whether a Number Is a Palindrome
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:
- Store the original number.
- Reverse the number using digit extraction.
- Compare the reversed number with the original.
- Return
truewhen they are equal; otherwise returnfalse.
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.