Skip to the code
cf.
+25 XP

#669 Adder Circuit Simulator

medium

A teaching app simulates how a CPU adds numbers using only logic gates. Write add32(a, b) that returns a + b without using the + or - operators, only bitwise operators.

The result must wrap around like a 32-bit signed integer, exactly as (a + b) | 0 would: for example, 2147483647 + 1 gives -2147483648.

Example 1

Input: a = 1, b = 2
Output: 3

01 ^ 10 = 11 and there is no carry, so the sum is 3.

Example 2

Input: a = -1, b = 1
Output: 0

In 32 bits, -1 is all ones. Adding 1 carries all the way out of bit 31, leaving 0.

Constraints

  • -2^31 <= a, b <= 2^31 - 1
  • Don't use +, -, ++, or -- in your solution.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).