使用 JavaScript 拆分数字以包含连续的奇数或偶数
问题
我们需要编写一个接受数字n(n>0)的JavaScript函数。我们的函数应该返回一个包含奇数或偶数连续部分的数组。这意味着当我们遇到不同的数字(奇数为偶数,偶数为奇数)时,我们应该在位置处拆分数字。
示例
以下是代码-
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 ]