DSA · Bit Manipulation · #172
Sum of Two Integers
Module 50 · difficulty 3/5·⏱ 30:00starts on first keystroke
Given two integers `a` and `b`, return their sum **without using the operators `+` and `-`**. Implement the function `getSum(a, b)` which returns the integer sum of `a` and `b` using only bitwise operations. The trick: `a ^ b` adds the bits **without** carrying, while `(a & b) << 1` is exactly the carry that addition produced. Feed the carry back in and repeat until there is no carry left. In JavaScript, applying `| 0` after each step coerces the value back to a 32-bit signed integer, which keeps negatives correct and guarantees the loop terminates.
Examples
a = 1, b = 2→3a = 2, b = 3→5— 2^3 = 1, carry (2&3)<<1 = 4; then 1^4 = 5, carry 0, done.a = -1, b = 1→0— Negative numbers work via two's complement bit arithmetic.
Constraints
- · -1000 <= a, b <= 1000
- · Inputs and outputs fit in a 32-bit signed integer
- · You may not use the `+` or `-` operators
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.