在 JavaScript 中寻找所有数字中的第 n 个回文数


问题

我们需要编写一个 JavaScript 函数来接收数字 n。我们的函数应该返回从 0 开始计数的第 n 个回文数。

例如,第一个回文数为 0,第二个为 1,第十个为 9,第十一个为 11,因为 10 不是回文数。

示例

代码如下 −

 实时演示

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));

Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.

输出

控制台输出如下 −

212

更新于: 2021-04-19

408 次浏览

开启您的职业生涯

通过完成课程获得认证

开始
广告