Sum of Two Integers Without Using '+' Operator

Medium Bit Manipulation

Problem

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

  • −10⁹ ≤ a, b ≤ 10⁹

Example

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

The straightforward addition using '+' is disallowed. Instead, the algorithm uses bitwise operations to simulate addition. XOR (^) computes the sum bits without carry, while AND (&) followed by a left shift (<< 1) computes the carry bits. Iteratively applying these operations accumulates the sum until no carry remains. For example, starting with a=1 (01) and b=2 (10): - XOR: 01 ^ 10 = 11 (sum without carry) - AND and shift: (01 & 10) << 1 = 00 (carry) Since carry is zero, the sum is 3 (11 in binary).

Approach

Straightforward Solution

Using the '+' operator directly adds the two numbers in O(1) time. However, the problem forbids '+' and '-', so this approach is invalid.

Core Observation

Addition can be decomposed into two parts: sum without carry and carry bits. XOR operation yields the sum bits ignoring carry, while AND operation identifies carry bits. Shifting the carry bits left aligns them for the next addition step.

Path to Optimal

The key recognition signals are 'sum without using +' and 'bitwise operations'. These indicate Bit Manipulation because addition can be simulated by combining XOR and AND operations iteratively. XOR computes the sum bits ignoring carry, and AND followed by left shift computes the carry bits. Repeating this process until carry is zero yields the final sum.

Optimal Approach

Use a loop that continues while the carry (b) is non-zero. In each iteration, compute carry as (a & b) << 1, update a as a ^ b (sum without carry), and update b as carry. When carry becomes zero, a contains the final sum. Masking with 0xffffffff simulates 32-bit integer overflow behavior, ensuring correct results for negative numbers in Python's unlimited integer representation.

Time

O(1)

The loop runs at most 32 times for 32-bit integers, as each iteration propagates carry bits one position to the left, guaranteeing termination in constant time.

Space

O(1)

Only a fixed number of integer variables and bitwise operations are used, requiring constant auxiliary space.

Pattern Spotlight

Bit Manipulation (Iterative Carry Propagation)

Addition without '+' can be achieved by iteratively combining sum bits (XOR) and carry bits (AND shifted left), propagating carry until none remains, effectively simulating binary addition at the bit level.

Solution

1class Solution:
2 def getSum(self, a: int, b: int) -> int:
3 mask = 0xffffffff
4
5 while (b & mask) > 0:
6 carry = (a & b) << 1
7 a = a ^ b
8 b = carry
9
10 return (a & mask) if b > 0 else a

Step-by-Step Solution

1

Simulate 32-bit Integer Behavior with Masking

3mask = 0xffffffff

Objective

To constrain the integers to 32-bit representation, simulating overflow and enabling correct handling of negative numbers in Python.

Key Insight

Python integers are unbounded, so bitwise operations can produce unexpected results for negative numbers. Applying a mask of 0xffffffff limits values to 32 bits, mimicking fixed-width integer behavior. This ensures that operations like carry propagation and final result extraction behave as expected for signed 32-bit integers.

Interview Quick-Check

Core Logic

Masking with 0xffffffff confines all intermediate results to 32 bits, enabling correct simulation of signed integer overflow.

Common Pitfalls & Bugs

Omitting the mask leads to infinite loops or incorrect results for negative inputs due to Python's unlimited integer size.

2

Iteratively Compute Sum and Carry Until No Carry Remains

5while (b & mask) > 0:
6 carry = (a & b) << 1
7 a = a ^ b
8 b = carry

Objective

To repeatedly update the sum and carry bits until the carry becomes zero, yielding the final sum.

Key Insight

Each iteration computes the carry bits by ANDing a and b and shifting left, while the sum bits are computed by XORing a and b. Updating a and b with these values simulates one step of binary addition. The loop continues until carry is zero, meaning no further bit propagation is needed and the sum is complete.

Interview Quick-Check

Core Logic

The loop uses XOR for sum bits and shifted AND for carry bits, iterating until carry is zero, which simulates binary addition without '+' operator.

State & Boundaries

The loop condition `(b & mask) > 0` ensures the process continues only while there are carry bits to propagate.

Common Pitfalls & Bugs

Incorrect loop condition or missing masking can cause infinite loops or incorrect results.

3

Return Final Result with Correct Sign Handling

10return (a & mask) if b > 0 else a

Objective

To return the final sum, correctly handling negative results by applying the mask conditionally.

Key Insight

After the loop, if carry bits remain positive, the result is masked to 32 bits to simulate signed integer behavior. Otherwise, the raw value of a is returned. This conditional return ensures that negative sums are represented correctly in Python's integer model, which differs from fixed-width integers in other languages.

Interview Quick-Check

Core Logic

The conditional return applies the mask to simulate 32-bit signed integer representation when carry bits are positive.

Common Pitfalls & Bugs

Failing to mask the result can cause incorrect sign representation for negative sums.

Line Analysis

This solution has 4 Critical lines interviewers watch for.

Line 6 Critical
carry = (a & b) << 1

Calculate carry bits by ANDing a and b, then shifting left.

AND identifies bits where both a and b have 1s, indicating a carry is needed; shifting left aligns these carry bits with the next higher bit position for addition in the next iteration.

Line 5 Critical
while (b & mask) > 0:

Continue loop while carry bits exist within 32-bit range.

The loop condition ensures the algorithm iterates only while there are carry bits to propagate, preventing infinite loops and guaranteeing termination.

Line 7 Critical
a = a ^ b

Compute sum bits without carry using XOR.

XOR adds bits without considering carry, effectively summing bits where only one of a or b has a 1, which is the core of bitwise addition.

Line 10 Critical
return (a & mask) if b > 0 else a

Return the final sum, applying mask if carry bits remain positive.

Applying the mask here ensures the result fits within 32 bits and correctly represents negative numbers in Python's integer model, which differs from fixed-width integers in other languages.

Line 3 Core
mask = 0xffffffff

Define a mask to limit integers to 32 bits.

This mask simulates 32-bit integer overflow behavior in Python, which uses arbitrary-length integers, ensuring bitwise operations behave as expected for signed 32-bit integers.

Line 8 Core
b = carry

Update b to the carry bits for the next iteration.

Assigning carry to b prepares the next iteration to add these carry bits, propagating them until no carry remains.

Test Your Understanding

Why does the algorithm use XOR for sum and AND followed by left shift for carry in each iteration?

XOR computes the sum bits without considering carry, while AND identifies positions where both bits are 1, indicating a carry is needed. Shifting carry left aligns it with the next higher bit position for addition in the next iteration.

Related Problems

Bit Manipulation pattern

Don't just read it. Drill it.

Reconstruct Sum of Two Integers Without Using '+' Operator from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Sum of Two Integers Without Using '+' Operator drill

or drill a free problem