3

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.

1 Answer 1

10

To derive the final answer, you need to know which bits have been used at least once, and which have been used at least twice. These two conditions can be computed very quickly:

unsigned usedOnce = 0;
unsigned usedTwice = 0;
for(int i = 0; i < n; i++) {
    usedTwice |= usedOnce & array[i];
    usedOnce |= array[i];
}
unsigned answer = usedOnce & ~usedTwice;

That's only three operations in the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.