Blind 75 · Bit Manipulation

Sum of Two Integers

Medium

Watch the walkthrough (5:18)

Problem

Return a + b without ever using + or - on the way there.
Both inputs are 32-bit signed integers and may be negative; the answer fits in 32 bits too.

Examples

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

Example 2:
Input: a = 2, b = 3
Output: 5

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

Example 4:
Input: a = -1, b = -1
Output: -2

Constraints

-1000 <= a, b <= 1000

Prerequisites

Binary and two's complement — how a negative number is stored, and what a shift does at the edges.
The trick worth memorising: n & (n-1) clears the lowest set bit.

How to think about it

1. XOR Is the Sum, AND Is the Carry Optimal

Intuition

Add in binary the way you add on paper, a column at a time. One bit and one bit: 0 + 0 is 0, 0 + 1 is 1, and 1 + 1 is 10, a 0 with a carry of 1 into the next place. The digit is a XOR b, and the carry is where both are 1, a AND b, one place to the left. So a ^ b is the sum with no carrying, and (a & b) << 1 is every carry at once, and adding those two is the same problem again: repeat until there is no carry. 2 + 3 is 010 + 011: a becomes 001 and the carry 100, then a becomes 101 and the carry 0, and the answer is 5. The carries' lowest place climbs at least one place a round, so 32 rounds always end it. Java's int has 32 places, and a carry out of bit 31 drops off by itself. Python's int has no top place: -2 is ones for ever to the left, so on -2 + 3 the carry climbs for ever and the loop never ends. So Python keeps 32 bits with a mask, 0xFFFFFFFF, on both inputs and on every carry: the carry out of bit 31 drops off as in Java, and -2 + 3 ends after 31 rounds at 1. Then it reads the answer signed: 2^31 or more has 2^32 taken off, so -1 + -1, which is 4294967294 in 32 bits, is -2. That subtraction is not part of the adding; it only reads 32 bits as a signed number. XOR adds without carrying; add the carries, shifted left, the same way.

Algorithm

1. In Python, mask a and b to 32 bits with 0xFFFFFFFF; Java's int is 32 bits already.
2. While b is not 0: the carry is a & b shifted left by one (in Python, masked to 32 bits); a becomes a ^ b; b becomes the carry.
3. Return a read signed: in Java it already is; in Python, take 2^32 off an answer of 2^31 or more.

Time & Space

Time O(1): at most 32 rounds. Space O(1).