Created
May 5, 2019 03:03
-
-
Save jovey-zheng/409bba2f9323e2bcf44ad1b9f6a757d6 to your computer and use it in GitHub Desktop.
Calculate the sum of large 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
/** | |
* @param a {String} | |
* @param b {String} | |
*/ | |
function sumBigNumber(a, b) { | |
if (typeof a !== 'string' || typeof b !== 'string') { | |
throw new Error('param 'a' and 'b' must be string') | |
} | |
var res = '', | |
temp = 0; | |
// split the string to an array | |
a = a.split(''); | |
b = b.split(''); | |
while (a.length || b.length || temp) { | |
// the value `true` is number `1` | |
// `~~undefined` is number `0` | |
temp += ~~a.pop() + ~~b.pop(); | |
res = (temp % 10) + res; | |
temp = temp > 9; | |
} | |
return res.replace(/^0+/, ''); | |
} | |
// invoke: sumBigNumber('9', '9') | |
// output: '18' | |
// invoke: sumBigNumber('123456789123456789', '123456187468716478236487263487623428374628764') | |
// output: '123456187468716478236487263611080217498085553' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment