使用 JavaScript 將數字拆分以包含連續的奇數或偶數


問題

我們需要編寫一個 JavaScript 函式,它接受一個數字 n(n>0)。我們的函式應當返回一個包含奇數或偶數連續部分的陣列。這意味著我們應當在遇到不同數字(奇數對於偶數,偶數對於奇數)時在相應位置拆分數字。

示例

以下是程式碼 −

 執行示例

const num = 124579;
const splitDifferent = (num = 1) => {
   const str = String(num);
   const res = [];
   let temp = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(!temp || +temp[temp.length - 1] % 2 === +el % 2){
         temp += el;
      }else{
         res.push(+temp);
         temp = el;
      };
   };
   if(temp){
      res.push(+temp);
      temp = '';
   };
   return res;
};
console.log(splitDifferent(num));

輸出

[ 1, 24, 579 ]

更新於:19-4-2021

224 瀏覽量

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.