Sum of Two Integers
The key idea
Binary addition splits into two independent pieces:
a XOR b is the sum without carry, and (a AND b) << 1 is the carry. Feed the carry back in and repeat until it is 0 — that loop reproduces + using only bitwise ops.Problem
Given two integers a and b, return the sum of the two integers without using the operators + and -.
You may use any other operator, including the bitwise operators (AND, OR, XOR, shifts). The idea is to rebuild addition from its two parts: the column-by-column sum and the carry.
Constraints
-1000 <= a, b <= 1000
Examples
Input: a = 1, b = 2
Output: 3
Input: a = -2, b = 3
Output: 1
Input: a = 5, b = 7
Output: 12
Complexity
Time: O(1) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization