在 JavaScript 中查詢一個範圍內的順序數字


順序數字

一個數字只有當且僅當數字中的每個數字比前一個數字多 1 時才具有順序數字。

問題

我們要求編寫一個 JavaScript 函式,該函式採用一個包含正好兩個元素並指定一個範圍的陣列 arr。

我們的函式應該返回一個已排序的陣列,其中包含 arr(包括極限)範圍內的所有具有順序數字的整數。

例如,如果函式的輸入是 -

const arr = [1000, 13000];

那麼輸出應該是 -

const output = [1234, 2345, 3456, 4567, 5678, 6789, 12345];

示例

程式碼如下 -

 演示

const arr = [1000, 13000];
const sequentialDigits = ([low, high] = [1, 1]) => {
   const findCount = (num) => {
      let count = 0;
      while(num > 0){
         count += 1
         num = Math.floor(num / 10)
      };
      return count;
   };
   const helper = (count, start) => {
      let res = start;
      while(count > 1 && start < 9){
         res = res * 10 + start + 1;
         start += 1;
         count -= 1;
      };
      if(count > 1){
         return 0;
      };
      return res;
   };
   const count1 = findCount(low);
   const count2 = findCount(high);
   const res = [];
   for(let i = count1; i <= count2; i++){
      for(let start = 1; start <= 8; start++){
         const num = helper(i, start);
         if(num >= low && num <= high){
            res.push(num);
         };
      };
   };
   return res;
};
console.log(sequentialDigits(arr));

輸出

控制檯中的輸出如下 -

[
   1234, 2345,
   3456, 4567,
   5678, 6789,
   12345
]

更新於:2021 年 4 月 7 日

333 次瀏覽

推動你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.