Write a C++ program that accepts input array from user and find the two unique number which occurred only once in array.
Example:
Input:
10
1 1 2 3 3 4 4 5 6 6
Output:
2 5
Explanation:
This problem can be solved using the concept of Bitwise XOR, Bitwise AND, and bit masking.
Bitwise XOR:
Bitwise XOR ( ^ ) takes two equal-length bit patterns. If both bits in the compared position of the bit patterns are 0 or 1, the bit in the resulting bit pattern is 0, otherwise 1.
Example:
A = 5 = 0101, B = 3 = 0011
A ^ B = 0101 ^ 0011 = 0110 = 6
Special Property of XOR:
A^A =0
A^0 = A
Bitwise AND
Bitwise AND ( ^ ) takes two equal-length bit patterns. The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0.
Example:
A = 5 = 0101, B = 3 = 0011
A & B = 0101 & 0011 = 0001 = 1
For the current problem:
- First we take XOR of all elements of array.
- Suppose we have: 1,1,2,3,3,4,4,5,6,6
- On taking XOR of all elements, this will remove duplicates elements as A ^A =0
Then we get: 2^5 from above result
- The result of 2^5 will definitely have at least a set bit, to find the rightmost set bit we do res&1 and make a count to take the record of current position. If we get a non-zero res&1 that's the position we want to get, break the loop, otherwise right shift the res and increment the count.
- Make a mask using 1<<count, and take & one by one with all elements, Elements resulting a non zero result of mask &arr[i], take XOR of them .
- Resulting XOR will result in firstNo.
- Now for SecondNo, take XOR of firstNo with initial res. i.e., firstNo^ firstNo ^ secondNo.
-
Program:
Output