Think of a+b = (a XOR b) + (a AND b)*2
as exactly what happen when you do binary addition. From your example, a = 010
and b = 111
:
010 111 ---1001 = 101 + 100
For each bit, you add bits from a
and b
(0+0=0
, 0+1=1
, 1+0=1
, 1+1=0
, which is exactly a XOR b
plus the carry-in bit from the previous addition, i.e. if both previous bits for a
and b
are 1, then we add it also. This is exactly (a AND b)*2
. (Remember that multiplication by 2 is a shift left.)
With that equation we can calculate a AND b
.
Now to count the number you want, we look at each bits of a XOR b
and a AND b
one-by-one and multiply all possibilities. (Let me write a[i]
for the i
-th bit of a
)
If
a[i] XOR b[i] = 0
anda[i] AND b[i] = 0
, thena[i] = b[i] = 0
. Only one possibility for this bit.If
a[i] XOR b[i] = 0
anda[i] AND b[i] = 1
, thena[i] = b[i] = 1
. Only one possibility for this bit.If
a[i] XOR b[i] = 1
anda[i] AND b[i] = 0
, thena[i] = 1
andb[i] = 0
or vice versa. Two possibilities.It's not possible to have
a[i] XOR b[i] = 1
anda[i] AND b[i] = 1
.
From your example, a XOR b = 101
and a AND b = 010
. We have the answer 2*1*2 = 4
.