Sum of array elements whose count of set bits are unique | C ++ program for the approach ; Function to count the number of set bits in an integer N ; Stores the count of set bits ; Iterate until N is non - zero ; Stores the resultant count ; Function to calculate sum of all array elements whose count of set bits are unique ; Stores frequency of all possible count of set bits ; Stores the sum of array elements ; Traverse the array ; Count the number of set bits ; Traverse the array And Update the value of ans ; If frequency is 1 ; Driver Code
#include <iostream> NEW_LINE #include <bits/stdc++.h> NEW_LINE using namespace std ; int setBitCount ( int n ) { int ans = 0 ; while ( n ) { ans += n & 1 ; n >>= 1 ; } return ans ; } int getSum ( int * arr , int n ) { map < int , int > mp ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int key = setBitCount ( arr [ i ] ) ; mp [ key ] += 1 ; } for ( int i = 0 ; i < n ; i ++ ) { int key = setBitCount ( arr [ i ] ) ; if ( mp [ key ] == 1 ) ans += arr [ i ] ; } cout << ans ; } int main ( ) { int arr [ 5 ] = { 8 , 3 , 7 , 5 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getSum ( arr , n ) ; return 0 ; }