Sum of Two Integers
Sum of Two Integers is a medium Bit Manipulation problem from the Blind 75. The key pattern is bitwise addition, and a good solution runs in O(32) time.
Problem
Return the sum of two signed 32-bit integers without using addition or subtraction operators.
Examples
Example 1
Input
[-12,7]Output
-5Example 2
Input
[1,2]Output
3Example 3
Input
[-1,1]Output
0Approach
XOR adds without carrying and AND shifted left gives the carry. Repeat until there is no carry left.
| Pattern | Bitwise addition |
|---|---|
| Time | O(32) |
| Space | O(1) |
Watch out for
Keep values in signed 32-bit range: | 0 in JavaScript, or mask with 0xffffffff in Python and convert back.