LeetCode ยท #371

Sum of Two Integers Solution

Calculate the sum of two integers without using + or -.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Medium

๐Ÿ”—

LeetCode

Problem #371

๐Ÿ—๏ธ

Pattern

Bit Manipulation โ€” half adder

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

Example
Input: a = 1, b = 2 Output: 3
Constraints
โ€ข -1000 โ‰ค a, b โ‰ค 1000
02
Section Two ยท Approach 1

Increment/Decrement Loop

Use ++ or -- in a loop. Technically cheating (these use + and - underneath) and O(|b|) slow.

The insight: Simulate a half-adder. XOR computes the sum without carry. AND + shift-left computes the carry. Repeat until no carry remains.
03
Section Three ยท Approach 2

Bit Manipulation (Half Adder) โ€” O(32) = O(1)

Three rules from digital logic:
โ€ข a XOR b = sum of each bit pair without carry
โ€ข (a AND b) << 1 = the carry produced by each bit pair
Repeat: a = a XOR b, b = carry, until carry == 0.

๐Ÿ’ก Mental model: Think of how you add numbers by hand column by column. XOR gives you what digit to write down (sum without carry). AND-then-shift gives you what to carry to the next column. You keep iterating until there's nothing left to carry โ€” then the XOR result is the final sum. At most 32 iterations for 32-bit ints.
Algorithm
  • While b != 0:
  • carry = (a AND b) << 1
  • a = a XOR b
  • b = carry
  • Return a.
๐ŸŽฏ When to recognize this pattern: "Add/subtract without arithmetic operators." This is the classic half-adder from digital circuits mapped to code. Also applies to LC 67 (Add Binary โ€” same idea with strings) and forms the basis of CPU adder circuits.
Python note: Python integers have arbitrary precision โ€” no 32-bit overflow. Must manually mask to 32 bits and handle sign extension. Use & 0xFFFFFFFF to keep 32 bits and convert back using ~(result ^ 0xFFFFFFFF) for negatives.
04
Section Four ยท Trace

Visual Walkthrough

Trace for a=3 (011), b=5 (101). Expected: 8 (1000).

Sum of Two Integers โ€” Half Adder Simulation
a=3 (011โ‚‚), b=5 (101โ‚‚). XOR=sum-no-carry. AND<<1=carry. Iter 1: a=011 XOR 101=110(6). carry=(011 AND 101)<<1 = 001<<1=010(2). a=6, b=2. Iter 2: a=110 XOR 010=100(8). carry=(110 AND 010)<<1=010<<1=100(4)... wait: a=6(110) XOR 2(010)=100(4... no). Let me recheck: 110โŠ•010=100=4. (110&010)=010<<1=100=4. a=4, b=4. Iter 3: a=100 XOR 100=000(0). carry=(100 AND 100)<<1=100<<1=1000(8). a=0, b=8. Iter 4: a=0 XOR 8=8. carry=0. b=0. Done โ†’ return 8 โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” Half adder loop
class Solution { public int getSum(int a, int b) { while (b != 0) { int carry = (a & b) << 1; // carry bits a = a ^ b; // sum without carry b = carry; // propagate carry } return a; } }
Python โ€” 32-bit masked half adder
class Solution: def getSum(self, a: int, b: int) -> int: MASK = 0xFFFFFFFF MAX = 0x7FFFFFFF while b & MASK: carry = ((a & b) << 1) & MASK a = (a ^ b) & MASK b = carry # Handle negative: if bit 31 set, extend sign return a if a <= MAX else ~(a ^ MASK)
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpaceNote
Loop ++/--O(|b|)O(1)Cheating; slow for large b
Half adder โ† optimalO(1) (โ‰ค32 iters)O(1)Carry propagates at most 32 positions
Why at most 32 iterations? Each iteration, the carry shifts left by 1 bit. After 32 shifts, the carry is always 0 (for 32-bit integers). In practice, it terminates much earlier โ€” when there are no more overlapping set bits.
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
One zeroa=5, b=0carry=0 immediately โ†’ return a=5.
Negative + positivea=-1, b=1Works in two's complement. XOR handles bit cancellation correctly.
Both negativea=-2, b=-3Two's complement XOR and carry logic works correctly for negatives in Java. Python needs masking.
Overflow boundarya=1000, b=1000Within 32-bit range โ†’ 2000. Fine.
โš  Common Mistake: In Python, integers are unbounded. Without masking to 0xFFFFFFFF, the carry can grow infinitely and the loop never terminates for negative numbers. Always mask: carry = ((a & b) << 1) & 0xFFFFFFFF and a = (a ^ b) & 0xFFFFFFFF. Then sign-extend the result if the top bit is set.

โ† Back to Math & Bit problems