Header Ad

HackerEarth A XOR value problem solution

In this HackerEarth A XOR value problem solution You are given an array A consisting of N integer values. Find an integer K such that the value of the following function is minimized:
  • Sigma(i=1,i=N) (A[i] XOR K), XOR represents a bitwise XOR operation
If multiple such K exist, then print the minimum possible value of K.


HackerEarth A XOR value problem solution


HackerEarth A XOR value problem solution.

#include<bits/stdc++.h>
#define ll long long int
using namespace std;

void solve(){
int n;
cin >> n;
assert(1 <= n and n <= 100000);

ll a[n+1];
for(int i = 1 ; i <= n ; i++)
{
cin >> a[i];
assert((ll)1 <= a[i] and a[i] <= 1000000000000000000);
}

ll k = 0;
for(int i = 0 ; i < 60 ; i++)
{
ll vl = (1LL << i);
int cnt = 0;
for(int j = 1 ; j <= n ; j++)
{
if(vl & a[j])
{
cnt++;
}
}

int ncnt = n - cnt;

if(cnt > ncnt)
{
k += vl;
}
}

cout << k << endl;
}

int main(){
int t;
cin >> t;
assert(1 <= t and t <= 10);
while(t--){
solve();
}
}

Second solution

MAXB = 60
t = int(input())
while t > 0:
t -= 1
n = int(input())
a = list(map(int, input().split()))
cnt = [[0, 0] for _ in range(MAXB)]
for x in a:
for i in range(MAXB):
cnt[i][x >> i & 1] += 1
print(sum((cnt[i][0] < cnt[i][1]) << i for i in range(MAXB)))

Post a Comment

0 Comments