Sum of Two Integers
MediumBit Manipulation
Given two integers a and b, return a + b without using the + or - operators (and without sum() or similar shortcuts). Use bitwise operations instead.
Negative numbers use the usual two's complement representation. Python integers have unlimited width, so to make negative values work you will need to simulate a fixed 32-bit width with a mask; the true sum always fits comfortably in 32 bits.
Example 1
- Input:
- a = 5, b = 7
- Output:
- 12
- Explanation
- In binary,
101 ^ 111 = 010is the sum without carries, and(101 & 111) << 1 = 1010is the carry. Repeating until the carry is 0 gives1100, which is 12.
Example 2
- Input:
- a = -3, b = 1
- Output:
- -2
- Explanation
- -3 is stored in two's complement. The same XOR-and-carry loop gives -2, as long as values are kept to a fixed 32-bit width.
Example 3
- Input:
- a = -8, b = -4
- Output:
- -12
- Explanation
- Both inputs are negative; the carry eventually shifts out of the 32-bit window and the result reads back as -12.
Constraints
-1000 <= a, b <= 1000