使用 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.