π Palindrome Number in JavaScript

π Palindrome Number in JavaScript
A palindrome is a word, phrase, or number that reads the same forward and backward.
β¨ Examples:
Words:
madam
,level
,radar
Numbers:
121
,1331
,444
Numbers like 123
or -121
β are not palindromes.
π§© Problem Statement
π Write a function that checks whether a number is a palindrome.
Input:
121
Output:
true
β (because reading it backwards still gives121
)
π₯οΈ Solution Approach
Weβll solve it using math (without converting to string) π
Steps:
If the number is negative β directly return
false
(since-121
β121-
).Store a copy of the number (
xCopy
).Reverse the digits of the number.
Use
% 10
to extract last digit.Multiply the reversed number by
10
and add the last digit.Use
Math.floor(n / 10)
to remove the last digit.
Compare reversed number with original copy.
If equal β itβs a palindrome.
Else β not a palindrome.
π§βπ» Code Implementation
function isPalindrome(x) {
// Step 1: Handle negatives
if (x < 0) return false;
// Step 2: Copy number
let xCopy = x;
let rev = 0;
// Step 3: Reverse digits
while (x > 0) {
let rem = x % 10; // last digit
rev = (rev * 10) + rem; // add to reversed
x = Math.floor(x / 10); // remove last digit
}
// Step 4: Compare
return rev === xCopy;
}
π Dry Run Example
π Input: 121
Step | x | rem | rev | Explanation |
Init | 121 | β | 0 | Start |
1 | 12 | 1 | 1 | rev = 0*10+1 β 1 |
2 | 1 | 2 | 12 | rev = 1*10+2 β 12 |
3 | 0 | 1 | 121 | rev = 12*10+1 β 121 |
Finally β rev(121) === xCopy(121)
β
Palindrome!
π― Test Cases
console.log(isPalindrome(121)); // true
console.log(isPalindrome(-121)); // false (negative numbers not palindromes)
console.log(isPalindrome(10)); // false (reverse = 01 β 1)
console.log(isPalindrome(1331)); // true
console.log(isPalindrome(123)); // false
π οΈ Alternate Approaches
Convert to String
function isPalindromeStr(x) { let str = x.toString(); return str === str.split("").reverse().join(""); }
β Short and simple, but less efficient (extra memory used).
Two-pointer technique on string
Compare first and last characters, then move inward.
π Key Takeaways
Palindrome check is a common coding interview problem.
Avoiding string conversion shows stronger algorithmic skills.
Practice variations:
Palindrome strings
Palindrome with spaces/ignoring cases (
"A man a plan a canal Panama"
)
β¨ You now have a clear understanding of how to check palindrome numbers in JavaScript β both mathematically and using strings.
Subscribe to my newsletter
Read articles from Kamlesh Choudhary directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
