Minimum number of elements to be removed to make XOR maximum using C++.

C++Server Side ProgrammingProgramming

Problem statement

Given a number N. The task is to find the minimum number of elements to be removed in between to N such that the XOR obtained from the remaining elements is maximum.

Algorithm

1. If n is 1 or 2 then there is no need to remove any element. Hence answer is zero
2. Find a number which is power of 2 and greater than or equal to. Let us call this number as nextNumber
   2.1. If n == nextNumber or n == (nextNumber – 1) then answer is 1
   2.2. If n = (nextNumber -2) then answer is 0
3. If n is an even then answer is 1 otherwise 2

Example

#include <iostream>
using namespace std;
int nextPowerOf2(int n){
   if (n && !(n & (n - 1))) {
      return n;
   }
   int cnt = 0;
   while (n) {
      n = n / 2;
      ++cnt;
   }
   return (1 << cnt);
}
int elmentsToBeRemoved(int n){
   if (n == 1 || n == 2) {
      return 0;
   }
   int nextNumber = nextPowerOf2(n);
   if (n == nextNumber || n == nextNumber -1) {
      return 1;
   } else if (n == nextNumber - 2) {
      return 0;
   } else if (n & 1) {
      return 2;
   } else {
      return 1;
   }
}
int main(){
   int n = 10;
   cout << "Numbers to be removed = " <<
   elmentsToBeRemoved(n) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Numbers to be removed = 1s
raja
Published on 31-Oct-2019 06:47:10
Advertisements