Sum of Two Integers
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
Sum of Two Integers
Given two integers
a and b, return the sum of the two integers without using the operators + and -.Examples
Input: a = 1, b = 2
Output: 3
Input: a = 2, b = 3
Output: 5
Approach 1
Level I: Brute Force (Bit-by-Bit Simulation)
Intuition
Simulate how a half-adder or full-adder works. Iterate through each bit position (0 to 31), calculate the sum of bits and the carry, and build the result bit by bit.
Thought Process
- Initialize
res = 0,carry = 0. - For
ifrom 0 to 31:- Get -th bits of
aandb. sum = bitA ^ bitB ^ carry.carry = (bitA & bitB) | (carry & (bitA ^ bitB)).- Set -th bit of
restosum.
- Get -th bits of
- Return
res.
Pattern: Simulation / Logic Gates
⏱ O(1) - Always 32 iterations.💾 O(1) - Constant space.
Approach 2
Level II: Recursive XOR & AND
Intuition
The iterative logic can be expressed recursively. The sum of
a and b is equivalent to the XOR of a and b (sum without carry) plus the AND of a and b shifted left (the carry).⏱ $O(1)$ - Max 32 recursive calls.💾 $O(1)$ - Recursion stack for 32 levels.
Approach 3
Level III: Optimal (Iterative XOR & AND)
Intuition
Addition can be broken into two parts: the sum without carry (
a ^ b) and the carry itself ((a & b) << 1). We repeat this process until the carry becomes zero.Thought Process
a ^ bgives the sum bits where no carry is involved.a & bgives the bits where a carry is generated.- Shift the carry left by 1 to add it to the next significant bit.
- Repeat until carry is 0.
Pattern: Recursive Addition Logic
⏱ O(1) - Max 32 iterations (number of bits).💾 O(1) - Constant space.
Detailed Dry Run
a = 2 (10), b = 3 (11)
- Iteration 1: sum = 10 ^ 11 = 01 (1) carry = (10 & 11) << 1 = 100 (4)
- Iteration 2: sum = 001 ^ 100 = 101 (5) carry = (001 & 100) << 1 = 000 (0) Result: 5
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.