0
0
0
1
1
[0][1][2][3][4]
XOR sum + carry
▸1// a + b without + or −2while b != 0:3 carry ← (a & b) << 1 // overflow columns4 a ← a ^ b // sum without carry5 b ← carry6return a
state
- a00011 = 3
- b00101 = 5
- rulesum = a^b, carry = (a&b)<<1
Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.
Try one problemCompute the sum a + b of two integers without using the + or − operators.
▸1// a + b without + or −2while b != 0:3 carry ← (a & b) << 1 // overflow columns4 a ← a ^ b // sum without carry5 b ← carry6return a
line 1Goal: a + b without + or −. Look at one column of binary addition: 0+0=0, 0+1=1, 1+0=1, 1+1=0 carry 1. Notice the result bit is exactly a ^ b (XOR), and a carry happens only where BOTH bits are 1 (a & b). So addition = XOR + carry, and we repeat until the carry is empty.