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,band the true sum all fit in a 32-bit signed integer: from-2147483648to2147483647.- 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
- The Unpaired Sock (Easy)
- Lit Lamps on a Binary Counter (Easy)
- Mirror a 32-bit Register (Easy)
- Compounding Sign-ups Total (Hard)