Created
October 16, 2017 19:25
-
-
Save KimSarabia/bf794c997c63f7900828f1c8d1b1ed11 to your computer and use it in GitHub Desktop.
Sum of Large Number Strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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