Answer the question
In order to leave comments, you need to log in
How to add 2 adjacent numbers in 1 line, with the condition that they are the same?
How to add 2 adjacent numbers in 1 line, with the condition that they are the same. For example, the line 111111 should turn into line 222 and then into 42.
Answer the question
In order to leave comments, you need to log in
function collapse(digits) {
if (typeof digits !== 'string') {
digits = '' + digits;
}
var result = '';
for (var i = 0; i < digits.length; i++) {
if (digits[i] === digits[i+1]) {
result += (parseInt(digits[i]) + parseInt(digits[i+1]));
i++;
} else {
result += digits[i];
}
}
if (digits.length === result.length) {
return result;
} else {
return collapse(result);
}
}
var test = 111111;
console.log(collapse(test));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question