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

后端 未结 2 1102
暗喜
暗喜 2020-12-15 09:40

I think the question may be a bit confusing. So, I\'ll try to explain it first.

Let\'s say the XOR and SUM of two numbers are given. (Note that there are multiple pa

2条回答
  •  难免孤独
    2020-12-15 10:05

    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 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.

提交回复
热议问题