We are given n binary numbers, each of k bits. We need to find a k bit binary number in which ith bit is set only if the ith bit was set in exactly one of the n given binary numbers. For example,
0010
0011
0100
1110
should give 1001 as answer.You need to only use bit-wise operations to achieve this. Here is my solution:
unsigned int array[n];//we have our 'n' numbers here
unsigned int answer=0,rxor=0,t1,t2;
for(int i=0; i<n; ++i)
{
t1 = answer;
answer ^= array[i];
t2 = (~t1) & answer;
answer &= ~(t2 & rxor);
rxor |= array[i];
}
The final answer will be stored in the answer variable. It uses a total of 7 bit-wise operations( 1 xor, 1 or, 2 negation, 3 and ) per iteration, making a total of 7*n operations. My question is, can the number of operations can be reduced further.