Skip to main content
edited tags
Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238
edited tags
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481
edited body
Source Link
kharandziuk
  • 819
  • 2
  • 9
  • 20

The implementation of the algorithm which adds two number in string form with arithmetic rules.

var assert = require('assert'); var strAdd = function(lnum, rnum) { lnum = lnum.split('').reverse(); rnum = rnum.split('').reverse(); var len = Math.max(lnum.length, rnum.length), acc = 0;0, res = []; for(var i = 0; i < len; i++) { var subres = Number(lnum[i] || 0) + Number(rnum[i] || 0) + acc; acc = ~~(subres / 10); // integer division res.push(subres % 10); } if (acc !== 0) { res.push(acc); } return res.reverse().join(''); }; assert(strAdd('1', '9') === '10'); assert(strAdd('1', '0') === '1'); assert(strAdd('5', '5') == '10'); assert(strAdd('2', '2') === '4'); assert(strAdd('20', '202') === '222'); 

Is there a better way(in terms of complexity) to achieve the same result? Any style advice is appreciated.

The implementation of the algorithm which adds two number in string form with arithmetic rules.

var assert = require('assert'); var strAdd = function(lnum, rnum) { lnum = lnum.split('').reverse(); rnum = rnum.split('').reverse(); var len = Math.max(lnum.length, rnum.length), acc = 0; res = []; for(var i = 0; i < len; i++) { var subres = Number(lnum[i] || 0) + Number(rnum[i] || 0) + acc; acc = ~~(subres / 10); // integer division res.push(subres % 10); } if (acc !== 0) { res.push(acc); } return res.reverse().join(''); }; assert(strAdd('1', '9') === '10'); assert(strAdd('1', '0') === '1'); assert(strAdd('5', '5') == '10'); assert(strAdd('2', '2') === '4'); assert(strAdd('20', '202') === '222'); 

Is there a better way(in terms of complexity) to achieve the same result? Any style advice is appreciated.

The implementation of the algorithm which adds two number in string form with arithmetic rules.

var assert = require('assert'); var strAdd = function(lnum, rnum) { lnum = lnum.split('').reverse(); rnum = rnum.split('').reverse(); var len = Math.max(lnum.length, rnum.length), acc = 0, res = []; for(var i = 0; i < len; i++) { var subres = Number(lnum[i] || 0) + Number(rnum[i] || 0) + acc; acc = ~~(subres / 10); // integer division res.push(subres % 10); } if (acc !== 0) { res.push(acc); } return res.reverse().join(''); }; assert(strAdd('1', '9') === '10'); assert(strAdd('1', '0') === '1'); assert(strAdd('5', '5') == '10'); assert(strAdd('2', '2') === '4'); assert(strAdd('20', '202') === '222'); 

Is there a better way(in terms of complexity) to achieve the same result? Any style advice is appreciated.

Source Link
kharandziuk
  • 819
  • 2
  • 9
  • 20
Loading