Find a number which give minimum sum when XOR with every number of array of integer in C++


Concept

With respect of given array Arr[] of non-negative integers, the task is to determine an integer X such that (Arr[0] XOR X) + (Arr[1] XOR X) + … + Arr[n – 1] XOR X is minimum possible.

Input 

Arr[] = {3, 4, 5, 6, 7}

Output 

X = 7, Sum = 10

Approach

So we will verify ‘i’th bit of every number of array in binary representation and consider and count those numbers containing that ‘i’th bit set to ‘1’ because these set bits will contribute to maximize the sum instead of minimize. As a result of this, we have to build this set ‘i’th bit to ‘0’ if count is greater than N/2 and if count is less than N/2 then the numbers having ‘i’th bit set are less and as a result of this it will not affect the answer. We know according to XOR operation on two bits, when A XOR B and both A and B are same then it provides result as ‘0’ so we will build that ‘i’th bit in our number (num) to ‘1’, as a result that (1 XOR 1) will give ‘0’ and minimize the sum.

Example

 Live Demo

// C++ implementation of the approach
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
void findX1(int arr1[], int n1){
   int* itr1 = max_element(arr1, arr1 + n1);
   int p1 = log2(*itr1) + 1;
   int X1 = 0;
   for (int i = 0; i < p1; i++) {
      int count1 = 0;
      for (int j = 0; j < n1; j++) {
         if (arr1[j] & (1 << i)) {
            count1++;
         }
      }
      if (count1 > (n1 / 2)) {
         X1 += 1 << i;
      }
   }
   long long int sum1 = 0;
   for (int i = 0; i < n1; i++)
      sum1 += (X1 ^ arr1[i]);
   cout << "X = " << X1 << ", Sum = " << sum1;
}
// Driver code
int main(){
   int arr1[] = { 3, 4, 5, 6, 7 };
   int n1 = sizeof(arr1) / sizeof(arr1[0]);
   findX1(arr1, n1);
   return 0;
}

Output

X = 7, Sum = 10

Updated on: 23-Jul-2020

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements