Skip to content
Optimal Lab

Math & Bits · 128Medium

Sum of Two Integers

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

Constraints

  • -1000 <= a, b <= 1000

Examples

getSum(1, 2)         ->  3
getSum(2, 3)         ->  5
getSum(-1, 1)        ->  0
getSum(0, 0)         ->  0    // both operands zero
getSum(-2, -3)       ->  -5   // both operands negative
getSum(1000, -1000)  ->  0    // the constraint bounds

Edge cases

  • Negative operands must work — two's complement handles this naturally.
Show the target complexity (spoiler)
Naive
There is no simpler correct approach — the constraint is the whole exercise.
Target
O(1) time (at most 32 iterations) — repeatedly combine the XOR sum with the shifted AND carry until no carry remains.

Solve it

By hand, in your editor. The runner checks answers and timing.

git clone https://github.com/sarmadkung/optimal-round
cd optimal-round
# open problems/12-math-bits/128-sum-of-two-integers.js
./practice c 128