Note that A + X == (A xor X) + ((A and X)<<1)
. So:
A xor X = A + X - ((A and X)<<1) = B + X
A - B = (A and X)<<1
And we have:
(A - B) and not (A<<1) = 0 (All bits in (A - B) are also set in (A<<1))
(A - B)>>1 = A and X
If the condition is met, for any integer Y that doesn’t have bits that are set in A, (((A – B)>>1) or Y) is a solution. If you want just one solution, you could use ((A – B)>>1), where Y = 0. Otherwise there is no solution.
int solve(int a, int b){
int x = (a - b) >> 1;
if ((a ^ x) == b + x)
return x;
else
return ERROR;
}