Skip to content

Sum of Two Integers

Medium Day 3 • Striver Blind 75

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

Example 1:

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

Example 2:

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

Constraints:

  • -1000 <= a, b <= 1000

Bitwise XOR calculates addition without carry; bitwise AND shifted left calculates carry.

Bitwise Operations (XOR + AND)


📊 Step-by-Step Execution (Mermaid Diagram)

Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”
graph TD
A["Input Integer / Bits"] --> B["Apply Bitwise Operation (AND / XOR / Shift)"]
B --> C{"Check Bit Condition"}
C -- "Condition Met" --> D["Update Bit Count / Result"]
C -- "Continue" --> E["Shift Bits (>>> 1 or & n-1)"]
E --> B
D --> F["Return Final Result"]

function getSum(a, b) {
while (b !== 0) {
let carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
  • Time Complexity: O(1)
  • Space Complexity: O(1)
  • Explanation: Iterative bitwise carry.

function getSum(a, b) {
while (b !== 0) {
let carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
  • Time Complexity: O(1)
  • Space Complexity: O(1)
  • Explanation: Bitwise sum using XOR and shift.

  1. Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
  2. Iterate & Evaluate: Process the input according to the boundary conditions.
  3. Update & Return: Compute the optimal answer and return early or at termination.

Use XOR for bitwise sum and AND shifted for carry until carry becomes zero.


  1. XOR gives sum without carry.
  2. AND left shifted by 1 gives carry.

👉 Solve this problem interactively in the DSA Lab