Count of even and odd set bit Array elements after XOR with K for Q queries | C ++ Program to count number of even and odd set bits elements after XOR with a given element ; Store the count of set bits ; Brian Kernighan 's algorithm ; Function to solve Q queries ; Store set bits in X ; Count set bits of X ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void keep_count ( int arr [ ] , int & even , int & odd , int N ) { int count ; for ( int i = 0 ; i < N ; i ++ ) { count = 0 ; while ( arr [ i ] != 0 ) { arr [ i ] = ( arr [ i ] - 1 ) & arr [ i ] ; count ++ ; } if ( count % 2 == 0 ) even ++ ; else odd ++ ; } return ; } void solveQueries ( int arr [ ] , int n , int q [ ] , int m ) { int even_count = 0 , odd_count = 0 ; keep_count ( arr , even_count , odd_count , n ) ; for ( int i = 0 ; i < m ; i ++ ) { int X = q [ i ] ; int count = 0 ; while ( X != 0 ) { X = ( X - 1 ) & X ; count ++ ; } if ( count % 2 == 0 ) { cout << even_count << " ▁ " << odd_count << " STRNEWLINE " ; } else { cout << odd_count << " ▁ " << even_count << " STRNEWLINE " ; } } } int main ( ) { int arr [ ] = { 2 , 7 , 4 , 5 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int q [ ] = { 3 , 4 , 12 , 6 } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; solveQueries ( arr , n , q , m ) ; return 0 ; }