preface

We know when the browser input 9999999999999999999999 + 9999999999999999999999, the result is a science and counting method. Often we do not need or understand scientific notation. So we need to implement a function to add large numbers.

Analysis of the

We can do this by taking a large number, breaking it up into small pieces and adding up small pieces. We manually simulate carrying by string if when it reaches 10, we keep the ones place, we keep the tens place and we add the carry place the next time we compute it

Code implementation

const addStrings = (num1, num2) = > {
  let i = num1.length - 1;
  let j = num2.length - 1;
  let add = 0;
  const answer = []
  while (i >= 0 || j >= 0|| add ! = =0) {
    const val1 = i >= 0 ? num1.charAt(i) - '0' : 0
    const val2 = j >= 0 ? num2.charAt(j) - '0' : 0
    const result = val1 + val2 + add
    answer.push(result % 10)
    add = Math.floor(result / 10)
    i -= 1
    j -= 1
  }
  return answer.reverse().join(' ')}Copy the code