| Viewed 205 times

How to find the Closest Palindrome Number in Javascript?


I need a function that returns the closest palindrome number to an integer. If two palindrome numbers tie in absolute distance, return the smaller number.

1 Answer
Mohammad Qandeel
Answered
9

Use this function to find the Closest Palindrome Number in Javascript

function closestPalindrome(num) {
 var _ = function(n) {
  var a = (''+n).split('');
  while (a.length > 1) {
   if (a.pop() != a.shift()) return false;
  }
  return true;
 };
 for (var i = 0; ; i++) {
  if (_(num-i)) return num-i;
  if (_(num+i)) return num+i;
 }
 return false;
}

Example

closestPalindrome(1) //1

closestPalindrome(10) //9

closestPalindrome(55) //55

 


Related Questions