Created
April 18, 2014 19:52
-
-
Save ChrisLTD/11061553 to your computer and use it in GitHub Desktop.
Add big integer strings, returns a string
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
function addBigInts(a, b) { | |
var result = ''; | |
var carry = 0; | |
// convert to arrays and flip around | |
a = a.split('').reverse(); | |
b = b.split('').reverse(); | |
// we have to loop through the longer number to add all the values | |
var longerNumber = (a.length > b.length) ? a : b; | |
longerNumber.map(function(val, i ,arr){ | |
// check to see if the index exists in the array | |
aVal = (typeof a[i] != 'undefined') ? a[i] : 0; | |
bVal = (typeof b[i] != 'undefined') ? b[i] : 0; | |
var sum = Number(aVal) + Number(bVal) + carry; | |
if(sum > 9){ | |
carry = 1; | |
sum = sum + ''; | |
result += sum[1]; | |
} else { | |
carry = 0; | |
result += sum + ''; | |
} | |
}); | |
// if we have a leftover carry digit, add 1 to the end | |
if(carry > 0){ | |
result = result + '1'; | |
} | |
// turn the results the right way around | |
result = result.split(''); | |
result.reverse(); | |
result = result.join(''); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment