Skip to content

Instantly share code, notes, and snippets.

@jovey-zheng
Created May 5, 2019 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jovey-zheng/409bba2f9323e2bcf44ad1b9f6a757d6 to your computer and use it in GitHub Desktop.
Save jovey-zheng/409bba2f9323e2bcf44ad1b9f6a757d6 to your computer and use it in GitHub Desktop.
Calculate the sum of large numbers.
/**
* @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