Quantcast
Channel: Given an XOR and SUM of two numbers, how to find the number of pairs that satisfy them? - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by dejvuth for Given an XOR and SUM of two numbers, how to find the number of pairs that satisfy them?

$
0
0

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 bplus 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 and a[i] AND b[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.

  • If a[i] XOR b[i] = 0 and a[i] AND b[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.

  • If a[i] XOR b[i] = 1 and a[i] AND b[i] = 0, then a[i] = 1 and b[i] = 0 or vice versa. Two possibilities.

  • It's not possible to have a[i] XOR b[i] = 1 and a[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.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>