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 pairs that may satisfy this.)
For example, If the XOR is 5
and the SUM is 9
there are 4
pairs satisfying the SUM and XOR. They are (2,?7)
, (3,?6)
, (6,?3)
, (7,?2)
. So 2+7=9
and 2^7=5
.
I just want to find the number of pairs that satisfies the SUM and XOR. So in the example I mentioned the answer 4
is enough. I don't need to know which pairs satisfy them.
I took this problem from here.
I checked for an answer here. It provides an O(n) solution which is not enough.
There is an Editorial that provides the solution on this problem. It can be found here. (Look for the solution of 627A)
The problem is that I can't understand the solution. From what I could sum up they used a formula like this,
(If there are two numbers a and b) then,
a+b = (a XOR b) + (a AND b)*2
How do I arrive to that? The rest of the steps are unclear to me.
If anyone could provide an idea on how to solve this or explain their solution, please help.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…