Sum of elements from an array having even parity | C ++ program to find the sum of the elements from an array which have even parity ; Function that returns true if x has even parity ; We basically count set bits https : www . geeksforgeeks . org / count - set - bits - in - an - integer / ; Function to return the sum of the elements from an array which have even parity ; If a [ i ] has even parity ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkEvenParity ( int x ) { int parity = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; parity ++ ; } if ( parity % 2 == 0 ) return true ; else return false ; } long sumlist ( int a [ ] , int n ) { long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( checkEvenParity ( a [ i ] ) ) sum += a [ i ] ; } return sum ; } int main ( ) { int arr [ ] = { 2 , 4 , 3 , 5 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sumlist ( arr , n ) ; return 0 ; }