Answer the question
In order to leave comments, you need to log in
How to add two nines in an array?
Let's say there are two arrays that need to be added, without converting to an integer.
let a = [9, 9, 9, 9],
b = [9, 9, 9];
return [1,0,9,9,8]
let max = Math.max(a.length - 1, b.length - 1);
for(let i = max; i >= 0; i--) {
a[i] + b[i]
}
Answer the question
In order to leave comments, you need to log in
Array.from(`${+a.join('') + +b.join('')}`, Number)
or
function sum(a, b) {
const result = [];
let overflow = false;
for (let i = 1; i <= Math.max(a.length, b.length); i++) {
const digit = (a[a.length - i] | 0) + (b[b.length - i] | 0) + overflow;
overflow = digit > 9;
result.unshift(digit % 10);
}
if (overflow) {
result.unshift(1);
}
return result;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question