Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active September 30, 2015 06:12
Show Gist options
  • Save softwarespot/0ea991dd737441081d9c to your computer and use it in GitHub Desktop.
Save softwarespot/0ea991dd737441081d9c to your computer and use it in GitHub Desktop.
Sum big numbers
function add(a, b) {
// A queue to enqueue the result (minus the remainder)
const queue = [];
// Store the remainder
let remainder = 0;
// Determine the largest array length
const maxLength = Math.max(a.length, b.length);
for (let i = maxLength - 1; i >= 0; i--) {
// +a[i] is a trick I picked up from another kata to convert to a number
// Note: || checks if a value exists; otherwise, defaults to zero
// i - maxLength + a.length is basically saying index value minus max length plus actual length e.g. (5 - 10) = -5 + 8 = 3
// (index 3 of first array)
const sum = (+a[i - maxLength + a.length] || 0) + (+b[i - maxLength + b.length] || 0) + remainder;
const value = (sum % 10);
remainder = (sum - value) / 10; // 25 - 5 / 10 = 2, so the remainder is 2
// Add to the queue e.g. remove 2 from 23 to give just 3
queue.unshift(value);
}
// Add any remainder to the queue
if (remainder > 0 && remainder < 10) {
queue.unshift(remainder);
}
// Join the queue and remove leading zeros
return queue.join('').replace(/(?:^0*)/, '');
}
console.log(add('1234567890', '1234567890'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment