Search code examples
javascriptintegerscientific-notation

Sum Big Integers


I'm currently stuck on a Codewars challenge that I can't get my head around:

Given a string representation of two integers, return the string representation of those integers, e.g. sumStrings('1','2') // => '3'

I've used the following code so far, but it fails on large number test cases as the number is converted into a scientific notation:

function sumStrings(a,b) {
  var res = +a + +b;
  return res.toString();
}

Any help would be much appreciated.

Edit:

Fiddle example: https://jsfiddle.net/ag1z4x7d/


Solution

  • The problem is that in that specific kata (IIRC), the numbers stored in a and b are too large for a regular 32 bit integer, and floating point arithmetic isn't exact. Therefore, your version does not return the correct value:

    sumStrings('100000000000000000000', '1')
    // returns '100000000000000000000' instead of '100000000000000000001'
    

    You have to make sure that this does not happen. One way is to do an good old-fashioned carry-based addition and stay in the digit/character based world throughout the whole computation:

    function sumStrings(a, b) {
       var digits_a = a.split('')
       var digits_b = b.split('')
       ...
    }