“Add a and b.” Easy enough: return a+b. Then I read the rest of the question. No plus signs. No minus signs. Oh.

For the record, I submitted return a+b and the judge accepted it. That got a laugh out of me. But the question was worth doing properly. It had to handle negative numbers too: 1 and 2 should give 3, while −2 and 3 should give 1.

Split the answer into a sum and a carry

Forget carries for a moment. For each bit, 1 and 1 should give 0, 1 and 0 should give 1, and two zeros should stay zero. That’s XOR. For example, 101 ^ 011 is 010. That’s part of what we need to add 5 and 3, but it’s clearly not 8 yet.

The missing part is easiest to see with 7 and 7. Both are 111 in binary. XOR gives zero because every pair of bits matches. But those three pairs of ones each produce a carry into the next column. AND finds the pairs, and shifting left moves their carries one place over: (111 & 111) << 1 gives 1110, or 14.

So we have two numbers to combine again: the sum without carries and the carries themselves. Keep going until there are no carries left.

1
2
3
4
5
6
7
def getSum(a,b):
jin = (a&b)<<1
zheng = (a^b)
if(jin==0):
return zheng
else:
return getSum(jin,zheng)

Then I tried a negative input

Python printed hex(-1) as -0x1. I’d been picturing a fixed-width register full of ones, FFFFFFFF, and Python was cheerfully doing arithmetic without that 32-bit boundary. My workaround was to keep only the low 32 bits at each step:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def getSum(a,b):
jin = (a&b)<<1
zheng = (a^b)
MASK = 0x100000000
MAX_INT = 0x7FFFFFFF
MIN_INT = MAX_INT + 1
jin = jin % MASK
zheng = zheng %MASK
if(jin==0):
if(zheng>>28==0xf):
zheng^=0xffffffff
zheng = ~zheng
return zheng
return zheng
else:
return getSum(jin,zheng)

That gave me the unsigned bit pattern I wanted. The last wrinkle was how to read it: if that pattern represents a negative signed integer, convert it back before returning it. The code above is my original attempt at that conversion.