Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Palindrome numbers in JavaScript
We are required to write a JavaScript function that takes in a number and determines whether or not it is a palindrome number.
Palindrome numbers ? A palindrome number is that number which reads the same from both left and right sides.
For example ?
343 is a palindrome number
6789876 is a palindrome number
456764 is not a palindrome number
Method 1: String Reversal Approach
The simplest approach is to convert the number to a string, reverse it, and compare with the original:
const isPalindromeString = num => {
const str = num.toString();
const reversed = str.split('').reverse().join('');
return str === reversed;
};
console.log(isPalindromeString(343)); // true
console.log(isPalindromeString(6789876)); // true
console.log(isPalindromeString(456764)); // false
true true false
Method 2: Mathematical Approach
For a pure mathematical solution without string conversion:
const isPalindrome = num => {
let length = Math.floor(Math.log(num) / Math.log(10) + 1);
while(length > 0) {
let last = Math.abs(num - Math.floor(num/10)*10);
let first = Math.floor(num / Math.pow(10, length - 1));
if(first != last){
return false;
};
num -= Math.pow(10, length-1) * first;
num = Math.floor(num/10);
length -= 2;
};
return true;
};
console.log(isPalindrome(343)); // true
console.log(isPalindrome(6789876)); // true
console.log(isPalindrome(456764)); // false
true true false
Method 3: Reverse and Compare
Another mathematical approach that reverses the entire number:
const isPalindromeReverse = num => {
const original = num;
let reversed = 0;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num = Math.floor(num / 10);
}
return original === reversed;
};
console.log(isPalindromeReverse(343)); // true
console.log(isPalindromeReverse(6789876)); // true
console.log(isPalindromeReverse(456764)); // false
true true false
Comparison
| Method | Simplicity | Performance | Memory Usage |
|---|---|---|---|
| String Reversal | High | Good | Higher (string creation) |
| Mathematical (digit comparison) | Medium | Good | Lower |
| Number Reversal | High | Good | Lower |
Conclusion
The string reversal method is the most readable and intuitive for checking palindrome numbers. For performance-critical applications, use the mathematical approaches to avoid string conversion overhead.
