Skip to content
DSA Patterns
Menu
Language
Bit ManipulationLC #3716 of 6← Previous

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Sum of Two Integers

Problem (restated)

Return a+b without using + or, operators.

Intuition

a^b is sum without carry; (a&b)<<1 is carry. Iterate until carry is 0.

Approaches

XOR + carry loop

Unverified
Time O(1) 32-bitSpace O(1)

Idea. Full-adder simulation over bits. Python needs 32-bit mask for negatives.

Walkthrough. 1+2 → 3; -1+1 → 0.

Trade-offs. Built-in + is fine in production; problem is a bit-op exercise.

Solution
export function getSum(a: number, b: number): number {
  while (b !== 0) {
    const carry = (a & b) << 1;
    a = a ^ b;
    b = carry;
  }
  // JS bitwise is 32-bit signed already for |0
  return a | 0;
}
export function getSum(a: number, b: number): number {
  while (b !== 0) {
    const carry = (a & b) << 1;
    a = a ^ b;
    b = carry;
  }
  // JS bitwise is 32-bit signed already for |0
  return a | 0;
}

Template connection

XOR is the sum without carry, and (a & b) << 1 is the carry. Repeat until the carry is 0. Python masks to 32 bits so a negative matches two’s complement.

Reflection

  • XOR is the sum with no carry. a & b, shifted left by one, is the carry. Stop when the carry is 0.
  • Negatives are two’s complement. In Python, mask the carry to 32 bits or the loop does not settle.
  • a + 0 is a. (-1) + 1 is 0. At the int boundary the mask is what keeps the carry inside the word.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Add 3+1 with bits only. XOR is sum without carry; (a&b)<<1 is carry.

0
0
1
1
1
2

a=011 b=001

Key:CurrentActive rangeMatchSettledEliminated