
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Nearest palindrome in JavaScript
We are required to write a function, say nearestPalindrome() that takes in a number n and returns a palindromic number that is nearest to the number n.
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
Basically, the approach will be, we divide the number into two halves (w.r.t. its length) and return the new number which is just the first half concatenated twice.
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
The output in the console will be −
232 23532 121 1221 44
- Related Articles
- Palindrome numbers in JavaScript
- Palindrome array - JavaScript
- Finding nearest Gapful number in JavaScript
- Finding points nearest to origin in JavaScript
- Nearest Prime to a number - JavaScript
- Distance to nearest vowel in a string - JavaScript
- Distance of nearest 0 in binary matrix in JavaScript
- Verification if a number is Palindrome in JavaScript
- Filtering array to contain palindrome elements in JavaScript
- Checking for permutation of a palindrome in JavaScript
- Counting steps to make number palindrome in JavaScript
- Joining strings to form palindrome pairs in JavaScript
- Rounding off numbers to some nearest power in JavaScript
- Finding nearest prime to a specified number in JavaScript
- Summing up digits and finding nearest prime in JavaScript

Advertisements