XOR of all elements of array with set bits equal to K | C ++ program to find Xor of all elements with set bits equal to K ; Function to find Xor of desired elements ; Initialize vector ; push required elements ; Initialize result with first element of vector ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorGivenSetBits ( int arr [ ] , int n , int k ) { vector < int > v ; for ( int i = 0 ; i < n ; i ++ ) { if ( __builtin_popcount ( arr [ i ] ) == k ) { v . push_back ( arr [ i ] ) ; } } int result = v [ 0 ] ; for ( int i = 1 ; i < v . size ( ) ; i ++ ) result = result ^ v [ i ] ; return result ; } int main ( ) { int arr [ ] = { 2 , 13 , 1 , 19 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << xorGivenSetBits ( arr , n , k ) ; return 0 ; }