371. Sum of Two Integers - Detailed Explanation
Problem Statement
Given two integers, a and b, return the sum of these two integers without using the addition (+
) or subtraction (-
) operators. The challenge is to compute the result using bit-level operations.
Example 1
Input:
a = 1, b = 2
Output:
3
Explanation:
The sum of 1 and 2 is 3.
Example 2
Input:
a = 2, b = 3
Output:
5
Explanation:
The sum of 2 and 3 is 5.
Constraints
- The integers a and b can be positive, negative, or zero.
- You cannot use the
+
or-
operators in your solution. - The solution should handle typical 32-bit integer operations.
Hints
-
Bit Manipulation Insight:
Use bitwise XOR (^
) to add two numbers without carrying. This operation simulates addition for each bit but does not account for the carry-over. -
Carry Calculation:
Use bitwise AND (&
) to identify which bit positions will generate a carry. Then, shift the carry left by one (using<<
) to add it to the next higher bit. -
Iterative or Recursive Approach:
The sum can be computed by iteratively updating the numbers until there is no carry left, or by using recursion that terminates when the carry becomes zero.
Approach: Bit Manipulation
Explanation
The key observation is that the sum of two integers can be broken into two parts:
- Non-carry sum:
Using the XOR operation (a ^ b
) adds the bits without considering any carry. - Carry bits:
Using the AND operation (a & b
) finds all positions where both bits are 1, meaning a carry is generated. Shifting this result left by one ((a & b) << 1
) gives the actual carry that must be added to the non-carry sum.
The algorithm then repeats the process:
- Let sum =
a ^ b
(non-carry addition). - Let carry =
(a & b) << 1
(carry bits). - Set a = sum and b = carry and repeat until carry becomes 0.
When there is no carry, the variable a contains the final sum.
Visual Example
Consider adding a = 2
and b = 3
:
- Binary representation:
- 2 → 10
- 3 → 11
Step 1:
- Non-carry sum:
a ^ b = 10 ^ 11 = 01
(which is 1 in decimal) - Carry:
(a & b) << 1 = (10 & 11 = 10) << 1 = 100
(which is 4 in decimal)
Now, update:
- a = 1
- b = 4
Step 2:
- Non-carry sum:
a ^ b = 001 ^ 100 = 101
(which is 5 in decimal) - Carry:
(a & b) << 1 = (001 & 100 = 000) << 1 = 000
(which is 0 in decimal)
Since the carry is 0, the final answer is a = 5.
Python Code
Java Code
Complexity Analysis
-
Time Complexity:
In the worst case, the loop may run O(n) times where n is the number of bits (typically 32 for a standard integer). So, the time complexity is O(1) with respect to the size of the integers. -
Space Complexity:
The solution uses O(1) extra space since only a fixed number of variables are used.
Step-by-Step Walkthrough
-
Initialization:
- Define a mask for 32-bit operations.
- Set a and b to the input integers.
-
Iteration:
- Calculate the non-carry sum using XOR.
- Calculate the carry using AND, then left-shift by one.
- Update a with the non-carry sum and b with the carry.
-
Termination:
- The loop ends when there is no carry left (i.e., b equals 0).
- If a is greater than the maximum 32-bit positive integer, convert it to a negative number using bitwise complement.
-
Return:
- a contains the final sum.
Common Mistakes and Edge Cases
-
Handling Negative Numbers:
Since Python uses unlimited precision for integers, you need to simulate 32-bit overflow using a mask. In Java, the integer type naturally uses 32 bits. -
Infinite Loop:
Ensure the loop eventually terminates when the carry becomes zero. -
Bit Masking:
Forgetting to mask intermediate results might lead to incorrect values in languages with fixed integer sizes.
Alternative Variations
-
Recursive Implementation:
Instead of iterating, you can implement the solution recursively until the carry is zero. -
Subtraction Variant:
A similar technique can be used to implement subtraction using bitwise operations, though the logic is a bit more involved.
Related Problems
GET YOUR FREE
Coding Questions Catalog