Last active
August 29, 2015 14:12
-
-
Save keune/ff1d9d56ef5ccb8af5d1 to your computer and use it in GitHub Desktop.
Sum strings as numbers
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 stringAdd(a, b) { | |
/* | |
* Adds two numbers, in a way you would do with pen and paper | |
* Since the numbers are kept as strings, it can handle really big numbers | |
* Useful when you need to calculate sum of two big integers that are bigger than Number.MAX_SAFE_INTEGER | |
*/ | |
a += '' , b += ''; | |
var res = [], carry = 0, lena = a.length, lenb = b.length; | |
if(lena > lenb) { | |
b = new Array(lena - lenb + 1).join('0') + b; | |
} else { | |
a = new Array(lenb - lena + 1).join('0') + a; | |
} | |
for(var i=Math.max(lena, lenb)-1; i>=0; i--) { | |
var add = +(a.charAt(i)) + +(b.charAt(i)) + carry; | |
res.push(add%10); | |
carry = (add - (add%10)) / 10; | |
} | |
if(carry) res.push(carry); | |
return res.reverse().join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment