M
M
MeMoJlor2021-11-17 15:50:47
JavaScript
MeMoJlor, 2021-11-17 15:50:47

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]

I am iterating over the array from the end
let max = Math.max(a.length - 1, b.length - 1);
for(let i = max; i >= 0; i--) {
    a[i] + b[i]
}

But how to add one after 9+9 to the next nine?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-11-17
@MeMoJlor

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 question

Ask a Question

731 491 924 answers to any question