Sum of array elements whose count of set bits are unique | Java 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
import java . util . * ; class GFG { static int setBitCount ( int n ) { int ans = 0 ; while ( n != 0 ) { ans += n & 1 ; n >>= 1 ; } return ans ; } static void getSum ( int [ ] arr , int n ) { Map < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int key = setBitCount ( arr [ i ] ) ; if ( mp . containsKey ( key ) ) mp . put ( key , mp . get ( key ) + 1 ) ; else mp . put ( key , 1 ) ; } for ( int i = 0 ; i < n ; i ++ ) { int key = setBitCount ( arr [ i ] ) ; if ( mp . containsKey ( key ) && mp . get ( key ) == 1 ) ans += arr [ i ] ; } System . out . print ( ans ) ; } public static void main ( String args [ ] ) { int [ ] arr = { 8 , 3 , 7 , 5 , 3 } ; int n = arr . length ; getSum ( arr , n ) ; } }