Find a value whose XOR with given number is maximum in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the number whose XOR operation with the given number is maximum.

We are assuming the number of bits here is 8.

The XOR operation of different bits gives you the 1 bit. And the XOR operation between the same bits gives you the 0 bit.

If we find the 1's complement of the given number, then that's the number we are looking for.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findNumberWithMaximumXOR(int X) {
   return ((1 << 8) - 1) ^ X;
}
int main() {
   int X = 4;
   cout << findNumberWithMaximumXOR(X) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

251

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 01-Feb-2021 12:08:36
Advertisements