Skip to content

Instantly share code, notes, and snippets.

@remydagostino
Created July 21, 2014 01:38
Show Gist options
  • Save remydagostino/6aabbe58ed07cf99a9b7 to your computer and use it in GitHub Desktop.
Save remydagostino/6aabbe58ed07cf99a9b7 to your computer and use it in GitHub Desktop.
Iterative Implementation
/**
* 654 + 59 = 713
* addArrayNumbers([6, 5, 4], [5, 9]) // [7, 1, 3];
*
* @param {Array} first
* @param {Array} second
* @return {Array}
*/
function addArrayNumbers(first, second) {
var result = [],
carry = 0,
maxLength = Math.max(first.length, second.length),
a, b, sum, i;
for (i = 1; i <= maxLength; i++) {
a = first[first.length - i] || 0;
b = second[second.length - i] || 0;
sum = a + b + carry;
if (sum >= 10) {
carry = 1;
}
else {
carry = 0
}
result.unshift(sum % 10);
}
if (carry > 0) {
result.unshift(1);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment