使用 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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP