Adder Circuit Without Plus

Medium · Bits & Math · about 25 min

You are simulating a tiny adder chip that only has AND, OR, XOR, NOT and shift gates. Write circuit_add(a, b) that returns a + b without using + or - (and without sum).

  • a, b and the true sum all fit in a 32-bit signed integer: from -2147483648 to 2147483647.
  • Negative numbers must work too.

Examples:

circuit_add(1, 3) → 4

circuit_add(-5, -7) → -12

Hints

  • XOR adds two bits without the carry. AND finds the columns that make a carry, and shifting left by one moves it to the next column.
  • Repeat with the partial sum and the carry until the carry is 0.
  • Python: integers have no 32-bit limit, so a negative carry never dies out. Keep every value inside 32 bits with a mask, and at the end turn a value with bit 31 set back into a negative number.

Learn the pattern first: the Bits & Math lesson.

More Bits & Math problems