Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Splitting number to contain continuous odd or even number using JavaScript
Problem
We need to write a JavaScript function that takes a positive number and splits it into continuous segments of odd or even digits. The function should create a new segment whenever it encounters a digit with different parity (odd becomes even or even becomes odd).
Example
For the number 124579:
- 1 (odd) - starts first segment
- 2, 4 (even) - starts second segment
- 5, 7, 9 (odd) - starts third segment
Solution
Following is the code:
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));
Output
[ 1, 24, 579 ]
How It Works
The algorithm converts the number to a string and iterates through each digit:
- Check if current digit has same parity as the last digit in temp
- If same parity, append to current segment (temp)
- If different parity, push current segment to result and start new segment
- Convert string segments back to numbers in the final array
Additional Examples
// Example with alternating digits console.log(splitDifferent(13579)); // All odd digits // Example with all even digits console.log(splitDifferent(2468)); // All even digits // Example with alternating pattern console.log(splitDifferent(135246)); // Mixed pattern
[ 13579 ] [ 2468 ] [ 135, 246 ]
Conclusion
This function efficiently splits numbers into continuous segments based on digit parity. It uses string manipulation and modulo operations to group consecutive odd or even digits together.
Advertisements
