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