Nearest power of 2 of frequencies of each digit of a given number | Java program for the above approach ; 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
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void nearestPowerOfTwoUtil ( HashMap < Character , Integer > freq ) { for ( char key : freq . keySet ( ) ) { System . out . print ( key + " ▁ - > ▁ " ) ; int lg = ( int ) ( Math . log ( freq . get ( key ) / Math . log ( 2 ) ) ) ; int a = ( int ) Math . pow ( 2 , lg ) ; int b = ( int ) Math . pow ( 2 , lg + 1 ) ; if ( ( freq . get ( key ) - a ) < ( b - freq . get ( key ) ) ) { System . out . println ( a ) ; } else { System . out . println ( b ) ; } } } static void nearestPowerOfTwo ( String S ) { int N = S . length ( ) ; HashMap < Character , Integer > freq = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { freq . put ( S . charAt ( i ) , freq . getOrDefault ( S . charAt ( i ) , 0 ) + 1 ) ; } nearestPowerOfTwoUtil ( freq ) ; } public static void main ( String [ ] args ) { String N = "16333331163" ; nearestPowerOfTwo ( N ) ; } }