Minimum operations to make XOR of array zero in C++

Problem statement

We are given an array of n elements. The task is to make XOR of whole array 0. We can do following to achieve this.

We can select any one of the element −

• After selecting element, we can either increment or decrement it by 1.
• We need to find the minimum number of increment/decrement operation required for the selected element to make the XOR sum of whole array zero

Example

If arr[] = {2, 4, 7} then 1 operation is required −

• Select element 2
• Decrement it by 1
• Now array becomes {3, 4, 7} and its XOR is 0

Algorithm

• Find the XOR of whole array
• Now, suppose we have selected element arr[i], so cost required for that element will be absolute(arr[i]-(XORsum^arr[i]))
• Calculating minimum of these absolute values for each of element will be our minimum required operation

Example

#include <iostream>
#include <climits>
#include <cmath>
using namespace std;
void getMinCost(int *arr, int n) {
int operations = INT_MAX;
int elem;
int xorValue = 0;
for (int i = 0; i < n; ++i) {
xorValue = xorValue ^ arr[i];
}
for (int i = 0; i < n; ++i) {
if (operations > abs((xorValue ^ arr[i]) - arr[i])) {
operations = abs((xorValue ^ arr[i]) - arr[i]);
elem = arr[i];
}
}
cout << "Element= " << elem << endl;
cout << "Minimum required operations = " << abs(operations) << endl;
}
int main() {
int arr[] = {2, 4, 7};
int n = sizeof(arr) / sizeof(arr[0]);
getMinCost(arr, n);
return 0;
}

Output

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

Element = 2
Minimum required operations = 1