Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.