InterviewPrepKit

Home / Coding / Bit Manipulation

Sum of Two Integers

medium Original ↗
Solving tips
  • Rebuild addition from bits: a ^ b is the sum with no carry, (a & b) << 1 is the carry; feed these back as new a and b and loop until the carry is 0.
  • The XOR term alone is the answer once carry becomes 0; at most 32 iterations, so O(1) time and O(1) space.
  • Python wrinkle: ints don't wrap, so negatives have infinite leading 1s and the loop never ends, mask with & 0xFFFFFFFF every iteration.
  • At the end reinterpret the sign: if result >= 0x80000000 return result - 0x100000000; pitfall is shifting the XOR instead of the AND, or masking only once up front.

Problem

Given two integers a and b, return their sum a + bwithout using the + or - operators (and without any helper that hides them, such as sum() or operator.add). Inputs and the result are signed 32-bit integers, and negative values are allowed.

The point is to rebuild addition itself out of bitwise operations.

Examples

  • a = 1, b = 23 01 + 10 = 11.
  • a = 2, b = 35 010 + 011 = 101.
  • a = -2, b = 31 Works across signs using 32-bit two’s-complement arithmetic.
  • a = -1, b = 10 The carries propagate all the way out and cancel.

Constraints

  • -1000 <= a, b <= 1000 on LeetCode, but the method must be correct for any signed 32-bit inputs [-2^31, 2^31 - 1].
  • You may not use + or -.
  • In Python, integers are arbitrary precision, so you must mask to 32 bits yourself and convert the result back to a signed value — the language will not overflow-wrap for you.

Think about it first

Hint 1 Recall how a schoolbook adds two binary numbers: add each column, and when a column overflows, carry a `1` into the next column. Which bitwise operator gives the column sum ignoring carries, and which one tells you where a carry is generated?
Hint 2 `a ^ b` is the sum of each bit position *without* carrying (`1 ^ 1 = 0`). `a & b` marks every position where both bits are `1` — exactly where a carry is born — and that carry lands one position to the left, so it is `(a & b) << 1`. Add those two together... but "add" is what you're building, so repeat.
Hint 3 Loop: `sum_no_carry = a ^ b`, `carry = (a & b) << 1`, then set `a = sum_no_carry`, `b = carry`, and repeat until `carry` is `0`. In Python, `&`-mask both to `0xFFFFFFFF` each iteration and, at the end, reinterpret a value `>= 2^31` as a negative number.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.