I was asked to implement this in an interview a while back. I didn't pass the interview, mostly likely because it took me far too long to do. However, I'm interested to know how well implemented the actual code is.
The task was to:
Add one to a positive number represented as an array of integers.
The question is the same as this one. However, I have done it in JavaScript and my implementation is different (recursion rather than loops), so I hope they are sufficiently different.
var addToArray = function(n){
var result = [];
function carryOne(n) {
if (n.length === 0) {
result.push(1);
}
else {
var length = n.length-1;
if (n[length] < 9) {
n[length] += 1;
result.push(n);
} else {
result.push(0);
carryOne(n.slice(0, length));
}
}
}
carryOne(n);
result.reverse();
var flatten = Array.prototype.concat.apply([], result);
console.log(flatten);
}
I've just noticed I have missed the semicolons on the closing braces on the function definitions but I'm keeping it like that for honesty.
In general it works but I think the need to reverse and flatten the array at the end is quite inelegant, so I suspect there is a better solution.