Count array elements whose highest power of 2 less than or equal to that number is present in the given array | C ++ program for the above approach ; Function to count array elements whose highest power of 2 is less than or equal to that number is present in the given array ; Stores the resultant count of array elements ; Stores frequency of visited array elements ; Traverse the array ; Calculate log base 2 of the element arr [ i ] ; Highest power of 2 whose value is at most arr [ i ] ; Increment the count by 1 ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countElement ( int arr [ ] , int N ) { int count = 0 ; unordered_map < int , int > m ; for ( int i = 0 ; i < N ; i ++ ) { m [ arr [ i ] ] ++ ; } for ( int i = 0 ; i < N ; i ++ ) { int lg = log2 ( arr [ i ] ) ; int p = pow ( 2 , lg ) ; if ( m [ p ] ) { count ++ ; } } return count ; } int main ( ) { int arr [ ] = { 3 , 4 , 6 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countElement ( arr , N ) ; return 0 ; }