371. Sum of Two Integers
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Bit Manipulation
- Time
- O(1)
- Space
- O(1)
Standard Solution (C++)
SummaryAdd two integers without using the plus or minus operators, relying only on bitwise operations.
Approach
Key idea: XOR adds bits without carrying, while AND shifted left by one produces the carry. Repeat until there is no carry left.
Steps:
- Compute carry = (a AND b) shifted left by 1.
- Compute a = a XOR b (sum ignoring carry).
- Set b = carry and loop until carry is zero.
- Use unsigned arithmetic for the carry shift to avoid signed-overflow undefined behavior.
class Solution {
public:
int getSum(int a, int b) {
while (b != 0) {
unsigned int carry = (unsigned int)(a & b) << 1;
a = a ^ b;
b = (int)carry;
}
return a;
}
}; Time O(1) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.