Find element with the maximum set bits in an array | Function to return the element from the array which has the maximum set bits ; To store the required element and the maximum set bits so far ; Count of set bits in the current element ; Update the max ; Driver code
function maxBitElement ( arr , n ) { let num = 0 , max = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { let cnt = BitCount ( arr [ i ] ) ; if ( cnt > max ) { max = cnt ; num = arr [ i ] ; } } return num ; } function BitCount ( n ) { let count = 0 ; while ( n != 0 ) { count ++ ; n &= ( n - 1 ) ; } return count ; } let arr = [ 3 , 2 , 4 , 7 , 1 , 10 , 5 , 8 , 9 , 6 ] ; let n = arr . length ; document . write ( maxBitElement ( arr , n ) ) ;