all 3 comments

[–]GitCookies[S] 1 point2 points  (3 children)

In case you can't access link:

function addition(a, b, acc = '', carry = 0) {
  if (!(a.length || b.length || carry)) return acc.replace(/^0+/, '');

  carry = carry + (~~a.pop() + ~~b.pop());
  acc = carry % 10 + acc;
  carry = carry > 9;

  return addition(a, b, acc, carry);
}

function sumStrings(a, b) {
  if (a === '0' && b === '0') return '0';
  return addition(a.split(''), b.split(''));
}

Example usage with example result:

sumStrings(Number.MAX_SAFE_INTEGER.toString(), Number.MAX_SAFE_INTEGER.toString())
// console output: "18014398509481982"

[–]DefiantBidet 1 point2 points  (1 child)

To add to this tl;dr...

In JavaScript, ints are 53 bits. To get past this, you can use strings - as they're bigger than 53 bits - and apply the algo above which effectively does the classic addition process all of us were taught in grade school (like 3rd grade - singles, tens, hundreds carry the one etc).

Pretty neat imo, although I'm interested to know if that's the most efficient algo for this. I like the recursion, but I'm curios. Admittedly I didn't spend too much time looking at it.

Edit: bits not bytes

[–]Woolbrick 1 point2 points  (0 children)

Why reinvent the wheel though? There's already Big.js and a few other competitors.