1

I am trying to solve a kata that seems to be simple on codewars but i seem to not be getting it right.

The instruction for this is as simple as below

Given the string representations of two integers, return the string representation of the sum of those integers.

For example:

sumStrings('1','2') // => '3'

A string representation of an integer will contain no characters besides the ten numerals "0" to "9".

And this is what i have tried

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

But the results solves all except two and these are the errors i get

sumStrings('712569312664357328695151392', '8100824045303269669937') - Expected: '712577413488402631964821329', instead got: '7.125774134884027e+26'

sumStrings('50095301248058391139327916261', '81055900096023504197206408605') - Expected: '131151201344081895336534324866', instead got: '1.3115120134408189e+29'

I don't seem to understand where the issues is from. Any help would help thanks.

Oke Tega
  • 908
  • 9
  • 18
  • Similar to this question? https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript – Peter M. Nov 09 '18 at 14:32
  • In this exercise you're expected to simulate a pen and paper addition, digit by digit. The simplest and most widely taught method is the column addition from the right. – georg Nov 09 '18 at 15:49

3 Answers3

9

The value you entered is bigger than the int type max value. You can try changing your code to:

 function sumStrings(a,b) { 
  return ((BigInt(a)) + BigInt(b)).toString();
}

This way it should return the right value

  • This is the correct answer but unfortunately the Kata he speaks of doesn't allow for BigInt to be used for some dumb reason. https://www.codewars.com/kata/5324945e2ece5e1f32000370/train/javascript – Gustavo Maximo Aug 18 '20 at 23:15
3

You could pop the digits and collect with a carry over for the next digit.

function add(a, b) {
    var aa = Array.from(a, Number),
        bb = Array.from(b, Number),
        result = [],
        carry = 0,
        i = Math.max(a.length, b.length);
        
    while (i--) {
        carry += (aa.pop() || 0) + (bb.pop() || 0);
        result.unshift(carry % 10);
        carry = Math.floor(carry / 10);
    }
    while (carry) {
        result.unshift(carry % 10);
        carry = Math.floor(carry / 10);
    }
    return result.join('');
}

console.log(add('712569312664357328695151392', '8100824045303269669937'));
console.log(add('50095301248058391139327916261', '81055900096023504197206408605'));
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0

The problem is that regular javascript integers are not having enough space to store that much big number, So it uses the exponential notation to not lose its precision

what you can do is split each number into parts and add them separately,

one such example is here SO answer

Shobi
  • 8,542
  • 5
  • 42
  • 64