codejump
MediumPro challengePythonJavaScriptTypeScript

Bits — Sum Without + or -

AlgorithmsBit ManipulationMath

solve(a, b) — return a + b without using the + or - operators. Both inputs and
the result fit in a signed 32-bit integer and may be negative.

This is how a CPU adds. XOR gives the sum of each bit position *ignoring carries*;
AND shifted left by one gives the carries. Add the two by repeating the same step
until no carry is left: a = a ^ b, b = (a & b) << 1 (computed from the *old* a).

In JavaScript the 32-bit operators handle negative numbers for free. Python integers are
unbounded, so mask them to 32 bits and convert back to a signed value at the end.

Examples

solve(1, 2)     → 3
solve(-1, 1)    → 0
solve(-5, -7)   → -12

Sample tests

Test #1Small positives
Input: [1,2]
Output: 3
Test #2Cancelling negative
Input: [-1,1]
Output: 0
Test #3Two negatives
Input: [-5,-7]
Output: -12