Problem overview
The method getSum receives two integers, a and b, and returns their sum without using the operators + and -. Both are between -1000 and 1000, and they can be negative.
For a = 1 and b = 2 the result is 3. For a = 2 and b = 3 it is 5. For a = -5 and b = 3 it is -2.
The lesson asks for bitwise operations, O(1) time (a loop of at most one turn per bit of a 32-bit integer) and O(1) extra space.
Approach: add column by column, as on paper
Add two binary numbers one column at a time. In one column, 0 + 0 = 0, 0 + 1 = 1, and 1 + 1 = 10: a 0 stays in the column and a 1 is carried into the next column to the left. Two facts follow:
- The digit left in each column is the XOR of the two bits, so
a ^ bis the sum with the carries left out. - A carry appears only in a column where both bits are 1, so the carries are
(a & b) << 1: the AND finds those columns and the shift moves each carry one column to the left.
The two numbers a ^ b and (a & b) << 1 still add up to the original sum, so repeat the process with them. Each round, the carries move at least one column to the left. Once there are no carries left, the XOR part is the full answer.
For 2 + 3 (010 and 011): the XOR is 001 and the carry is 100. The next round XORs those to 101 with no carry left. The sum is 101, which is 5.
Why Python needs a mask
This works directly in languages where an int has 32 bits. Python's integers have no fixed size, and a negative number behaves as if it had endless 1 bits on the left. Carries then never fall off the left end. For a = -1 and b = 1 without any mask, (a, b) goes (-2, 2), (-4, 4), (-8, 8), and so on, and b never reaches 0.
The fix is to work on the lowest 32 bits only. The value 0xFFFFFFFF is 32 one bits, and x & mask keeps the lowest 32 bits of x. A carry that moves past bit 31 is cut off, as it would be in a 32-bit int, so after at most 32 rounds b is 0.
The price is the end of the loop. The result in a is now a number between 0 and 4294967295 whose bit 31 may be set, which stands for a negative number in two's complement. The last step turns it back into a negative Python integer.
Step by step
- Define the mask. Store
0xFFFFFFFFinmask. The prefix0xstarts a hexadecimal number, and eachFis four 1 bits. - Loop while
b != 0. Hereaholds the sum so far andbthe carries still to add. When no carries remain, the sum is all ina. - Compute the carries.
carry = ((a & b) << 1) & mask: the columns where both bits are 1, moved one place left, then cut to 32 bits. - Add without carries.
a = (a ^ b) & mask. - Feed the carries back.
b = carry, so the next round adds them in. Computecarrybefore changinga, because it needs the olda. - Handle a negative result. After the loop, if
a > 0x7FFFFFFF, bit 31 is set, which means a negative number in a 32-bitint. Return~(a ^ mask). - Otherwise return
a. Its top bit is 0, so it is already the right number.
The solution in Python
class Solution:
def getSum(self, a: int, b: int) -> int:
mask = 0xFFFFFFFF
while b != 0:
carry = ((a & b) << 1) & mask
a = (a ^ b) & mask
b = carry
if a > 0x7FFFFFFF:
return ~(a ^ mask)
return a
Python details worth knowing
- The negative conversion.
a ^ maskflips the 32 low bits ofa. The~operator then flips every bit, including the infinite run above bit 31, which turns them into 1s. The result is the negative number those 32 bits stand for. Fora = 0xFFFFFFFE,a ^ maskis 1, and~1is-2. - Negative inputs are fine.
a & maskon a negative number gives its 32-bit two's complement form:-5 & 0xFFFFFFFFis4294967291, which is0xFFFFFFFB. - Python has no 32-bit overflow, so the mask is what imitates it. Results outside the 32-bit signed range wrap:
getSum(2147483647, 1)returns-2147483648. The lesson's inputs stay within -1000 to 1000, so this never happens there. - Hexadecimal literals.
0x7FFFFFFFis 2147483647, the largest 32-bit signed value.
Trace on a = -5, b = 3
Running the solution, a and b hold these values after each round of the loop:
| Round | a | b |
|---|---|---|
| 1 | 0xfffffff8 | 0x00000006 |
| 2 | 0xfffffffe | 0x00000000 |
The loop ends with a = 0xFFFFFFFE. That is above 0x7FFFFFFF, so the method returns ~(a ^ mask), which is -2.
Complexity
Time: each round moves the lowest carry at least one place to the left, and the mask cuts off anything beyond 32 bits, so the loop runs at most 32 times, whatever the input. That is O(1). For -1 and 1 it uses all 32 rounds.
Space: a few numbers are kept, so the extra space is O(1).
Edge cases and common mistakes
- Both zero.
bis 0 at the start, the loop never runs, and the method returns0. - Opposite numbers. For
a = -1andb = 1, the carry travels all the way up and falls off bit 31, leavinga = 0. The result is0. - Two negatives. For
a = -7andb = -8the result is-15. - Leaving out the mask. With a negative input, the loop doesn't end, as shown above.
- Returning
aunchanged at the end. For a negative sum this returns a large positive number such as4294967294instead of-2. - Updating
abefore computingcarry. The carry must come from the oldaandb; changingafirst gives wrong carries.
Testing
These results come from running the solution:
| a | b | Result |
|---|---|---|
| 1 | 2 | 3 |
| 2 | 3 | 5 |
| -5 | 3 | -2 |
| 0 | 0 | 0 |
| -1 | 1 | 0 |
| -7 | -8 | -15 |
