xxxxxxxxxx
// JavaScript Program to find the closest Palindrome
// number
// function check Palindrome
function isPalindrome(n)
{
for (let i = 0; i < Math.floor(n.length / 2); i++)
if (n[i] != n[n.length - 1 - i])
return false;
return true;
}
// convert number into String
function convertNumIntoString(num)
{
// base case:
if (num == 0)
return "0";
let Snum = num + '';
return Snum;
}
// function return closest Palindrome number
function closestPalindrome(num)
{
// case1 : largest palindrome number
// which is smaller to given number
let RPNum = num - 1;
while (!isPalindrome(convertNumIntoString(Math.abs(RPNum))))
RPNum--;
// Case 2 : smallest palindrome number
// which is greater than given number
let SPNum = num + 1;
while (!isPalindrome(convertNumIntoString(SPNum)))
SPNum++;
// check absolute difference
if (Math.abs(num - RPNum) > Math.abs(num - SPNum))
return SPNum;
else
return RPNum;
}
// Driver program to test above function
let num = 121;
console.log(closestPalindrome(num),"</br>");
// This code is contributed by prophet1999