Skip to content

Instantly share code, notes, and snippets.

@kerimdzhanov
Created December 16, 2015 15:34
Show Gist options
  • Save kerimdzhanov/c1b7924a8b594a86d852 to your computer and use it in GitHub Desktop.
Save kerimdzhanov/c1b7924a8b594a86d852 to your computer and use it in GitHub Desktop.
/**
* Sum two big numbers given as strings.
*
* @param {string} a
* @param {string} b
* @return {string}
*/
function sumStrings(a, b) {
var zrx = /^0+/; // remove leading zeros
a = a.replace(zrx, '').split('').reverse();
b = b.replace(zrx, '').split('').reverse();
var result = [], max = Math.max(a.length, b.length);
for (var memo = 0, i = 0; i < max; i++) {
var res = parseInt(a[i] || 0) + parseInt(b[i] || 0) + memo;
result[i] = res % 10;
memo = (res - result[i]) / 10;
}
if (memo) {
result.push(memo);
}
return result.reverse().join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment