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 problem
0
Problem

Sum of Two Integers

LeetCode #371Medium
XOR sum + carry · add without +

Compute the sum a + b of two integers without using the + or − operators.

Asked atAmazonGoogleBloomberg
step 1 / 10
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 columns
4 a ← a ^ b // sum without carry
5 b ← carry
6return a
state
  • a00011 = 3
  • b00101 = 5
  • rulesum = a^b, carry = (a&b)<<1

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.