Sum of Two Integers

35 min · getSum()

An adder circuit doesn't own a + key. It combines electrical bits, passes each carry to the next position, and still gets the same total.

Given two integers a and b, return their sum without using the + or - operators.

You may use bitwise operations. Work with signed 32-bit behavior:

  • XOR combines two bits without carrying.
  • AND finds positions that need a carry — a value transferred into the next binary position when both current bits are 1.
  • Negative values use two's complement, the standard signed-binary encoding where the highest bit marks a negative number.

Constraints

  • -1_000 <= a, b <= 1_000
  • The result fits in a signed 32-bit integer.
  • Your solution must not use the + or - operators.

Hints

Split one addition into two jobs

a ^ b gives the partial sum where carries are ignored. a & b marks every position where both inputs had a 1.

Move the carry

Shift (a & b) left by one. That shifted value is the carry still waiting to be added. Repeat with the partial sum until no carry remains.

Bound Python's bits

Python integers have no fixed width, so a negative value behaves as if it had infinitely many leading 1s. Masking to 32 bits means keeping only the lowest 32 positions; do that after every step, then reinterpret bit 31 as a sign at the end.

Follow-up

Can you explain why the carry must become zero within 32 rounds, even when one or both inputs are negative?

Visible cases

Examples

Example 1

ready
Input
a = 1
b = 2
Expected
3
Why
one XOR round plus its carry produces 3

Example 2

ready
Input
a = -2
b = 3
Expected
1
Why
the 32-bit carry process works across zero

Example 3

ready
Input
a = -5
b = -7
Expected
-12
Why
two negative two's-complement values still add normally

Interview signal

Asked at

AmazonGoogleBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite