Finding the nth palindrome number amongst whole numbers in JavaScript


Problem

We are required to write a JavaScript function that takes in number n. Our function should return the nth palindrome number if started counting from 0.

For instance, the first palindrome will be 0, second will be 1, tenth will be 9, eleventh will be 11 as 10 is not a palindrome.

Example

Following is the code −

 Live Demo

const num = 31;
const findNthPalindrome = (num = 1) => {
   const isPalindrome = (num = 1) => {
      const reverse = +String(num)
      .split('')
      .reverse()
      .join('');
      return reverse === num;
   };
   let count = 0;
   let i = 0;
   while(count < num){
      if(isPalindrome(i)){
         count++;
      };
      i++;
   };
   return i - 1;
};
console.log(findNthPalindrome(num));

Output

Following is the console output −

212

Updated on: 19-Apr-2021

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements