Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

functionsumStrings(a, b) {                                    // sum for any lengthfunctioncarry(value, index) {                             // cash & carryif (!value) {                                          // no value no funreturn;                                            // leave shop
        }
        this[index] = (this[index] || 0) + value;              // add valueif (this[index] > 9) {                                 // carry necessary?
            carry.bind(this)(this[index] / 10 | 0, index + 1); // better know this & go onthis[index] %= 10;                                 // remind me later
        }
    }

    var array1 = a.split('').map(Number).reverse(),            // split stuff and reverse
        array2 = b.split('').map(Number).reverse();            // here as well

    array1.forEach(carry, array2);                             // loop baby, shop every itemreturn array2.reverse().join('');                          // return right ordered sum
}

document.write(sumStrings('999', '9') + '<br>');
document.write(sumStrings('9', '999') + '<br>');
document.write(sumStrings('1', '9999999999999999999999999999999999999999999999999999') + '<br>');

Solution 2:

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:

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

Post a Comment for "Sum Big Integers"