Skip to content

Instantly share code, notes, and snippets.

@KimSarabia
Created October 16, 2017 19:25
Show Gist options
  • Save KimSarabia/bf794c997c63f7900828f1c8d1b1ed11 to your computer and use it in GitHub Desktop.
Save KimSarabia/bf794c997c63f7900828f1c8d1b1ed11 to your computer and use it in GitHub Desktop.
Sum of Large Number Strings
//Source: https://codereview.stackexchange.com/questions/92966/multiplying-and-adding-big-numbers-represented-with-strings
function add(a, b) {
if ((a | 0) == 0 && (b | 0) == 0) {
return '0';
}
a = a.split('').reverse();
b = b.split('').reverse();
var result = [];
for (var i = 0; (a[i] >= 0) || (b[i] >= 0); i++) {
var sum = (parseInt(a[i]) || 0) + (parseInt(b[i]) || 0);
if (!result[i]) {
result[i] = 0;
}
var next = ((result[i] + sum) / 10) | 0;
result[i] = (result[i] + sum) % 10;
if (next) {
result[i + 1] = next;
}
}
return result.reverse().join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment