0
I need to create a JS program that takes a user’s digit frequency (eg 11223655871) and returns the sequence with '-' between even numbers and '#' between odd numbers, that is, the result will be: 1#12-2365#587#1
0
I need to create a JS program that takes a user’s digit frequency (eg 11223655871) and returns the sequence with '-' between even numbers and '#' between odd numbers, that is, the result will be: 1#12-2365#587#1
1
var num=11223655871;
var result="";
var digits = num.toString().split('');
var realDigits = digits.map(Number);
for(i = 0; i < realDigits.length; i++)
{
var value1 = realDigits[i];
var value2 = realDigits[i+1];
result += value1;
if(value1 % 2 != 0 && value2 % 2 != 0) {
result += "#";
}else if(value1 % 2 == 0 && value2 % 2 == 0){
result += "-";
}
}
result = result.substring(0,(result.length - 1));
console.log(result);
Concepts:
0
You can use the Array.prototype.reduce function, look at the last character of the first argument and the second argument, see if they are the two odd/pairs, and return the number with potentially the symbol in the middle.
0
I believe regular expression is the best way to format your string.
let meuNum = 11223655871;
let numFormatdo = `${meuNum}`.replace(/([13579])([13579])/g, '$1#$2')
.replace(/([02468])([02468])/g, '$1-$2');
console.log(numFormatdo);
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.
The result would not be
1#1#2-2-3#6-5#5#8-7#1#
or there is another condition not explained in the question?– user76097
No, '-' is only inserted between even numbers and '#' between odd numbers. Between an even number and an odd number no value is entered.
– TiagoOliveira86
understood, between TWO even numbers and between TWO odd numbers
– user76097