Count array elements whose highest power of 2 less than or equal to that number is present in the given array | Java 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
import java . util . HashMap ; import java . io . * ; class GFG { static int log2 ( int N ) { int result = ( int ) ( Math . log ( N ) / Math . log ( 2 ) ) ; return result ; } static int countElement ( int arr [ ] , int N ) { int count = 0 ; HashMap < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( m . containsKey ( arr [ i ] ) ) { m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; } else { m . put ( arr [ i ] , 1 ) ; } } for ( int i = 0 ; i < N ; i ++ ) { int lg = log2 ( arr [ i ] ) ; int p = ( int ) Math . pow ( 2 , lg ) ; if ( m . containsKey ( p ) ) { count ++ ; } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 4 , 6 , 9 } ; int N = arr . length ; System . out . println ( countElement ( arr , N ) ) ; } }