XOR of all elements of array with set bits equal to K in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of n elements and an integer value k. Our task is to find XOR of all elements of the array that have set bits equal to k.

Let’s take an example to understand the problem,

Input

array = {2, 12, 44, 103, 17} , K =3

Output

44

To solve this problem, we will count set bit of every element of the array and compare it with k. If the number of set bits is equal to k, then we will push it to a vector and find XOR of all elements of the vector.

For finding the set bit count we will use __builtin_popcount() which is a built-in function in c++.

Program to show the implementation of our solution,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int XorKSetBits(int arr[], int n, int k){
   vector<int> kBitElments;
   for (int i = 0; i < n; i++) {
      if (__builtin_popcount(arr[i]) == k) {
         kBitElments.push_back(arr[i]);
      }
   }
   int result = kBitElments[0];
   for (int i = 1; i < kBitElments.size(); i++)
      result ^= kBitElments[i];
   return result;
}
int main(){
   int arr[] = { 2, 12, 44, 103, 17 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int k = 3;
   cout<<"XOR of all element of the array with "<<k<<" set bits is : "<<XorKSetBits(arr, n, k);
   return 0;
}

Output

XOR of all element of the array with 3 set bits is : 44
raja
Published on 17-Apr-2020 15:33:18
Advertisements