Created
July 21, 2014 01:38
-
-
Save remydagostino/6aabbe58ed07cf99a9b7 to your computer and use it in GitHub Desktop.
Iterative Implementation
This file contains 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
/** | |
* 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