Problem overview
The function getSum receives two integers, a and b, and must return a + b without using the operators + and -. The values are between -1000 and 1000, and negative numbers are allowed.
For a = 1 and b = 2 the answer is 3. For a = 2 and b = 3 it is 5, and for a = -5 and b = 3 it is -2.
The lesson asks for O(1) time and O(1) extra space: the loop may run once for each bit of the integer type, but no more.
Approach: add column by column, as on paper
Adding in binary works like adding in decimal, one column at a time. In a column, 0 + 0 is 0, 0 + 1 is 1, and 1 + 1 is 10: a 0 stays in that column and a 1 is carried to the next one on the left.
That gives two bitwise pieces:
a ^ b(XOR) is the digit left in each column, which is the sum with the carries left out.(a & b) << 1is the carries: a carry appears only where both numbers have a 1, and it belongs one column to the left.
The two results still add up to a + b, so the problem has been replaced by a similar one with a smaller carry. Repeat: XOR them, compute their carries, and stop when there are no carries left. Then the whole sum is in the XOR part.
For a = 2 and b = 3 (binary 010 and 011), the values after each round of the loop are:
a = 1 b = 4
a = 5 b = 0
result 5
In the first round the middle column has two 1s, so it leaves a 0 and carries a 1 to the left. In the second round, 1 and 100 share no column, nothing is carried, and a holds 5.
Negative numbers need no special case. Go stores them in two's complement, and this column-by-column addition is the one a processor does itself. With a = -5 and b = 3 the loop prints:
a = -8 b = 6
a = -2 b = 0
result -2
Step by step
- Start a loop that runs while
b != 0. Hereaholds the sum so far andbthe carries still to add. In Go, aforwith only a condition is the while loop. - Compute the carries and store them in
carry, declared with:=:(a & b) << 1. - Set
atoa ^ b, the sum without the carries. - Set
btocarry, so the next round adds those carries toa. The order matters:carrymust be computed beforeais overwritten, because it needs the olda. - Return
aonce no carries are left.
The solution in Go
func getSum(a int, b int) int {
for b != 0 {
carry := (a & b) << 1
a = a ^ b
b = carry
}
return a
}
The Go details worth knowing:
intis 64 bits. The loop therefore ends within 64 rounds: each round moves the lowest carry at least one place left, and after enough rounds it falls off the left end.- Shifts drop bits silently. A carry pushed past the top bit disappears. That is what ends the loop for the hardest case, described below.
^between two numbers is XOR. The same symbol in front of a single number flips its bits.- Parameters are copies. The function changes
aandbfreely without touching the caller's variables.
The longest case
The slowest inputs are a negative number and a positive one of the same size. With a = -1 and b = 1, every round produces a single carry that moves one place left, so the values run through a = -2, b = 2, then a = -4, b = 4, and so on. After 64 rounds the carry has moved off the left end:
a = -9223372036854775808 b = -9223372036854775808
a = 0 b = 0
result 0
That is the last two rounds, and the answer, 0, is right. The loop is still bounded by the width of the type, which is why the algorithm is O(1).
Complexity
Time: O(1). The loop runs at most once per bit of an int, 64 times, whatever a and b are. Each round does a constant number of bit operations.
Space: O(1). The function keeps a, b and carry.
Edge cases and common mistakes
- Zero.
getSum(0, 0)skips the loop and returns 0. Ifbis 0 from the start,ais returned as it is. - Opposite numbers.
getSum(7, -7)andgetSum(-1, 1)both return 0. - The extremes.
getSum(-1000, -1000)returns -2000 andgetSum(1000, 1000)returns 2000. - Overwriting
atoo early. Ifa = a ^ bruns before the carry is computed, the carry is built from the wrong value ofa. - Forgetting the shift. A carry belongs in the next column. Using
a & bwithout<< 1adds it in the wrong place. - Handling negatives separately. Not needed; adding a special case only adds bugs.
Testing
a = 1,b = 2gives3.a = 2,b = 3gives5.a = -5,b = 3gives-2.a = 0,b = 0gives0.a = -1,b = 1gives0.a = -1000,b = -1000gives-2000.
