Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* 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
You can’t perform that action at this time.