1
\$\begingroup\$

This implementation uses ECMA6 syntax and babel as transpiler. You can use this code to add integers which are bigger than Number.MAX_SAFE_INTEGER.

var _ = require('underscore'),
    assert = require('assert');

var strAdd = function(lnum, rnum) {
  var {rem, res} = _.chain(
    _.zip(
      lnum.split('').reverse(),
      rnum.split('').reverse()
    )
  ).reduce(
    ({rem, res}, [left, right]) => {
      var sum = Number(left || 0) + Number(right || 0) + rem;
      res.push(
        sum % 10
      );
      return {
        res,
        rem: ~~(sum/ 10)
      };
    },
    {
      rem: 0,
      res: []
    }
  ).value();
  if (rem !== 0) {
    res.push(rem);
  }
  return res.reverse().join('');
};
assert(strAdd('1', '9') === '10', strAdd('1', '9'));
assert(strAdd('1', '0') === '1', strAdd('1', '0'));
assert(strAdd('5', '5') == '10');
assert(strAdd('2', '2') === '4');
assert(strAdd('20', '202') === '222');
\$\endgroup\$
2
  • 1
    \$\begingroup\$ This is not Long arithmetic but Variable precision arithmetic! \$\endgroup\$
    – N74
    Commented Nov 3, 2015 at 15:14
  • \$\begingroup\$ That's much better. \$\endgroup\$
    – Joseph
    Commented Nov 3, 2015 at 16:23

1 Answer 1

1
\$\begingroup\$

Input validation

The function will happily return non-sense result when an argument contains not only digits. Unless you are absolutely certain that this function is used in a safe context, it would be good to validate the inputs.

Going even further, I would create a validate function that returns a number or else throws an exception, and call it after splitting:

  lnum.split('').map(validate).reverse(),
  rnum.split('').map(validate).reverse()

This way the summing step will not need anymore the Number conversions, a bit simpler:

  var sum = (left || 0) + (right || 0) + rem;

Cleverness

I find this clever, but hacky:

rem: ~~(sum/ 10)

I suggest to just spell out the intention nicely:

rem: sum > 9 ? 1 : 0

On the other hand, instead of this:

if (rem !== 0) {

Since the value of rem is guaranteed to be either 0 or 1, I think it's totally fine to be lazy and rely on the truthiness:

if (rem) {
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.