Skip to content
ΣDSA Patterns
Menu
Language

Bit Manipulation

Guide 6 of 6 · Path 6 of 6

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

Tested only
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

Bitwise arithmetic simulation.

Reflection