# 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