Skip to content

Instantly share code, notes, and snippets.

@D1360-64RC14
Created October 31, 2021 21:38
Show Gist options
  • Save D1360-64RC14/4cd23fd85c437d848549001cede5293d to your computer and use it in GitHub Desktop.
Save D1360-64RC14/4cd23fd85c437d848549001cede5293d to your computer and use it in GitHub Desktop.
Desafio: realizar uma soma de inteiros sem utilizar operador +
function sum(a, b) {
[xored, carry] = _sum_step(a, b)
while(carry) {
[xored, carry] = _sum_step(xored, carry)
}
return xored
}
function _sum_step(a,b) {
xored = a ^ b
carry = (a & b) << 1
return [xored, carry]
}
// Testes
for(i = 0; i < 1000; i++) {
for(j = 0; j < 1000; j++) {
console.assert(
(i + j) === sum(i, j),
`${i} + ${j} = ${i+j} (got ${sum(i, j)})`
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment