Created
October 31, 2021 21:38
-
-
Save D1360-64RC14/4cd23fd85c437d848549001cede5293d to your computer and use it in GitHub Desktop.
Desafio: realizar uma soma de inteiros sem utilizar operador +
This file contains hidden or 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
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