Bit Wise Comaprisn
Bit Wise Comaprisn
ishpreetsaluja02
Read
Discuss
Courses
Practice
Given two n-bit integers a and b, find the maximum possible value of (a’ xor b’)
where a’ is a shuffle-a, b’ is a shuffle-b and xor is the bitwise xor operator.
Examples:
Input: n = 3, a = 5, b = 4
Output: 7
Explanation: a = (101)2, b = (100)2, a’ = (110)2 , b’ = (001)2 and a’ xor b’ =
(111)2
Input: n = 5, a = 0, b = 1
Output: 16
Explanation: a = (00000)2 , b = (00001)2 a’ = (00000)2 , b = (10000)2 and a’ xor b’
= (10000)2
We want to maximize our answer, hence we find out the maximum number of 1’s it can
contain. In XOR operations, if a particular bit position has a 1 in one number and
a 0 in the other number, the result will have a 1 in that position (1^0=1 and
0^1=1). So, we find the maximum number of 1-0 and 0-1 pairs. The function min(1’s
in a , 0’s in b) gives the maximum 1-0 pairs possible and the function min(0’s in a
, 1’s in b) gives the maximum 0-1 pairs possible. Their sum will give the maximum
number of 1’s possible in our answer.
Example: n = 4, a = 10, b = 13 a’ = 1010, b’ = 1101
Minimum(set bit count in a, zeroes in b) = 1, Minimum(set bit count in b, zeroes in
a) = 2
Total set bits in a’ xor b'(sum) -> 1 + 2 = 3
One of the possible a’ and b’ combinations is a’=1001, b’= 0111 a’ xor b’ = 1110 =
14, which is the maximum possible value.
It is clear that 3 is the total number of bits to maximize xor.
Inside the for loop, it computes the maximum possible value of a’ xor b’ by placing
all the set bits(= to sum) in the beginning followed by zeroes
Below is the implementation of the above approach:
double XOR = 0;
// Drivers code
int main()
{
int n, a, b;
n = 3, a = 5, b = 4;
// Functional call
cout << MaximumXor(a, b, n) << "\n";
return 0;
}
Output
7