Skip to content

Instantly share code, notes, and snippets.

@mxschmitt
Created April 26, 2020 14:50
Show Gist options
  • Save mxschmitt/a6d857eec7f3b37b6b14172658859d13 to your computer and use it in GitHub Desktop.
Save mxschmitt/a6d857eec7f3b37b6b14172658859d13 to your computer and use it in GitHub Desktop.
Possible solution for the sum interview question
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