Problem overview
The method GetSum receives two int values, a and b, and returns a + b without using the + or - operators. Only bitwise operators are allowed. Both numbers can be negative: the inputs run from -1000 to 1000.
For 1 and 2 the answer is 3, for 2 and 3 it is 5, and for -5 and 3 it is -2.
Approach: add column by column, as on paper
Adding in binary works like adding in decimal. 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 on the left.
Two bitwise operations capture both parts at once:
a ^ b(XOR) is the digit left in each column: 0 for 0+0 and 1+1, and 1 for 0+1. It is the sum with the carries left out.(a & b) << 1is the carries. AND keeps a bit only where both numbers have a 1, which is exactly where a carry is produced, and shifting left by one moves each carry to the column it goes into.
The two results still add up to a + b. So repeat the same step on them: XOR gives a new partial sum, AND-and-shift gives new carries. A carry can itself cause another carry, but each round moves the lowest remaining carry at least one column to the left. When no carries are left, the partial sum is the answer.
Step by step
- Loop while
b != 0. Hereaholds the sum so far andbholds the carries still to be added. Whenbis 0, everything is ina. - Compute the carries:
int carry = (a & b) << 1;. This must happen beforeachanges, because it needs the old values of both numbers. - Update the sum without carries:
a = a ^ b;. - Hand the carries to the next round:
b = carry;. - Return
a.
Here are the values of a and b at the end of each round for 2 + 3:
a=1 b=4
a=5 b=0
In round one, the middle column has a 1 in both numbers: 2 & 3 is 010, so the carry is 100, which is 4, and 2 ^ 3 is 1. In round two there is no overlap between 1 and 4, so no carries remain and the sum is 5.
The solution in C#
class Solution {
public int GetSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
}
The C# details worth knowing:
- Negative numbers need no special case. An
intis stored in two's complement, and this column-by-column addition is the same one the processor performs. For-5 + 3the rounds end ata=-8 b=6and thena=-2 b=0. - Parameters are copies. The loop changes
aandb, but the caller's variables stay as they were. - Left shift discards the top bit.
<<on anintnever throws: a carry that leaves the 32 bits simply disappears. That is why the loop always ends, and why a sum that doesn't fit in 32 bits wraps. - Overflow wraps.
GetSum(int.MaxValue, 1)returns -2147483648, the same value that ordinaryintaddition produces without acheckedcontext. The lesson's inputs are small, so it doesn't come up there.
Complexity
Time: O(1). Each round moves the carries at least one column to the left, and an int has 32 columns, so the loop runs at most 32 times however large the values are. Space: O(1). Three int variables.
Edge cases and common mistakes
- Zero.
GetSum(0, 0)returns 0, and the loop never starts. - Opposite numbers.
GetSum(-1, 1)andGetSum(1000, -1000)both return 0. - Two negatives.
GetSum(-7, -8)returns -15. - Changing
abefore computing the carry.a ^ bdestroys the information about where both had a 1, so the carries come out wrong. - Forgetting the shift.
a & bmarks the columns that produce a carry, but the carry belongs one column to the left. - Using
+or-anyway. The exercise's point is the bitwise form: the loop above uses only&,^,<<and comparison.
Testing
a = 1, b = 2gives3.a = 2, b = 3gives5.a = -5, b = 3gives-2.a = -1, b = 1gives0.a = -7, b = -8gives-15.
