309/670

309. Sum of Two Integers

Medium

Your function receives two integers a and b and returns their sum — but you are not allowed to use the + or - operators anywhere in the computation.

Everything else is fair game: bitwise AND, OR, XOR, NOT, and shifts. Negative inputs must work too, exactly as 32-bit two's-complement hardware would add them.

Think about how a processor's adder circuit actually combines two numbers.

Example 1:

Input: a = 1, b = 2

Output: 3

Explanation: In binary, 01 XOR 10 = 11 and there is no carry, so the sum is 3 in a single step.

Example 2:

Input: a = -2, b = 3

Output: 1

Explanation: Two's-complement bit tricks handle mixed signs for free: the carries ripple until the answer 1 remains.

Constraints:

  • -1000 ≤ a ≤ 1000
  • -1000 ≤ b ≤ 1000
  • The + and - operators may not be used to combine the inputs.

Hints:

Add 5 and 3 in binary on paper, column by column. Each column produces a sum bit and possibly a carry bit — which bitwise operators produce each of those?

XOR gives the per-bit sum ignoring carries; AND marks exactly the columns that generate a carry. Where does a carry land relative to the column that produced it?

Repeat: a = a XOR b (sum without carries), b = (a AND b) << 1 (the carries), until b becomes 0. In Python, mask to 32 bits or negative numbers loop forever.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: a = 1, b = 2

Expected output: 3