Created
December 16, 2015 15:34
-
-
Save kerimdzhanov/c1b7924a8b594a86d852 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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