Nearest power of 2 of frequencies of each digit of a given number | Function to find the nearest power of 2 for all frequencies in the Map freq ; Traverse the Map ; Calculate log of the current array element ; Find the nearest power of 2 for the current frequency ; Function to find nearest power of 2 for frequency of each digit of num ; Length of string ; Stores the frequency of each character in the string ; Traverse the string S ; Function call to generate nearest power of 2 for each frequency ; Driver Code
function nearestPowerOfTwoUtil ( freq ) { freq . forEach ( ( value , key ) => { document . write ( key + " " ) ; var lg = parseInt ( Math . log2 ( value ) ) ; var a = Math . pow ( 2 , lg ) ; var b = Math . pow ( 2 , lg + 1 ) ; if ( ( value - a ) < ( b - value ) ) { document . write ( a + " " ) ; } else { document . write ( b + " " ) ; } } ) ; } function nearestPowerOfTwo ( S ) { var N = S . length ; var freq = new Map ( ) ; for ( var i = 0 ; i < N ; i ++ ) { if ( freq . has ( S [ i ] ) ) { freq . set ( S [ i ] , freq . get ( S [ i ] ) + 1 ) } else { freq . set ( S [ i ] , 1 ) } } nearestPowerOfTwoUtil ( freq ) ; } var N = " " ; nearestPowerOfTwo ( N ) ;