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
Nearest palindrome in JavaScript
We are required to write a function that takes in a number n and returns a palindromic number that is nearest to the number n. A palindrome reads the same forwards and backwards.
For example:
If the input number is 264, then the output should be 262
If the input number is 7834, then the output should be 7887
Approach
The approach divides the number into two halves based on its length and creates a palindrome by mirroring the first half. For odd-length numbers, the middle digit remains unchanged.
Example
const findNearestPalindrome = num => {
const strNum = String(num);
const half = strNum.substring(0, Math.floor(strNum.length/2));
const reversed = half.split("").reverse().join("");
const first = strNum.length % 2 === 0 ? half : strNum.substring(0,
Math.ceil(strNum.length/2))
return +(first+reversed);
};
console.log(findNearestPalindrome(235));
console.log(findNearestPalindrome(23534));
console.log(findNearestPalindrome(121));
console.log(findNearestPalindrome(1221));
console.log(findNearestPalindrome(45));
Output
232 23532 121 1221 44
How It Works
Let's break down the algorithm with an example:
const findNearestPalindrome = num => {
const strNum = String(num);
console.log(`Input: ${num}, String: "${strNum}"`);
const half = strNum.substring(0, Math.floor(strNum.length/2));
console.log(`First half: "${half}"`);
const reversed = half.split("").reverse().join("");
console.log(`Reversed half: "${reversed}"`);
const first = strNum.length % 2 === 0 ? half : strNum.substring(0,
Math.ceil(strNum.length/2));
console.log(`Complete first part: "${first}"`);
const result = +(first+reversed);
console.log(`Final palindrome: ${result}<br>`);
return result;
};
findNearestPalindrome(235);
findNearestPalindrome(1234);
Input: 235, String: "235" First half: "2" Reversed half: "2" Complete first part: "23" Final palindrome: 232 Input: 1234, String: "1234" First half: "12" Reversed half: "21" Complete first part: "12" Final palindrome: 1221
Key Points
For even-length numbers: Split in half and mirror the first half
For odd-length numbers: Keep the middle digit and mirror the first half
The
+operator converts the string result back to a number
Conclusion
This approach creates palindromes by mirroring the first half of a number. It works efficiently for most cases but may not always find the truly nearest palindrome for all inputs.
