Created
April 26, 2020 14:50
-
-
Save mxschmitt/a6d857eec7f3b37b6b14172658859d13 to your computer and use it in GitHub Desktop.
Possible solution for the sum interview question
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
const sum(a, b) => { | |
const maxLength = Math.max(a.length, b.length) | |
const out = [] | |
for (let i = 0, carry = false; i < maxLength || carry; i++) { | |
const numA = i < a.length ? parseInt(a[a.length - 1 - i], 10) : 0 | |
const numB = i < b.length ? parseInt(b[b.length - 1 - i], 10) : 0 | |
const sum = numA + numB + (carry ? 1 : 0) | |
carry = sum >= 10 | |
out.unshift(sum % 10) | |
} | |
return out.join('') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment