在 JavaScript 中查詢自然數序列的第 n 位數字


自然數序列

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12...

無限延長的序列即稱為自然數序列。

我們需要編寫一個 JavaScript 函式,它將一個數字 num 作為第一個也是唯一的引數。該函式應該查詢並返回當此序列以不帶逗號和空格的形式書寫時,在其中出現的第 (num) 個數字。

例如 -

如果輸入數字為 -

const num = 13;

那麼輸出應為 -

const output = 1;

因為 '1234567891011' 這個字串的第 13 個數字為 1

示例

程式碼如下 -

 線上演示

const num = 13;
const findDigit = (num = 1) => {
   let str = '';
   let i = 1;
   while(str.length < num){
      str += i;
      i++;
   };
   const required = str[num - 1];
   return required;
};
console.log(findDigit(num));

輸出

控制檯輸出如下 -

1

更新於:03-Mar-2021

476 次瀏覽

開啟您的職業

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.