Nearest power of 2 of frequencies of each digit of a given number | C # 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
using System ; using System . Collections . Generic ; class GFG { static void nearestPowerOfTwoUtil ( Dictionary < char , int > freq ) { foreach ( KeyValuePair < char , int > entry in freq ) { char key = entry . Key ; Console . Write ( key + " ▁ - > ▁ " ) ; int lg = ( int ) ( Math . Log ( freq [ key ] / Math . Log ( 2 ) ) ) ; int a = ( int ) Math . Pow ( 2 , lg ) ; int b = ( int ) Math . Pow ( 2 , lg + 1 ) ; if ( ( freq [ key ] - a ) < ( b - freq [ key ] ) ) { Console . Write ( a + " STRNEWLINE " ) ; } else { Console . Write ( b + " STRNEWLINE " ) ; } } } static void nearestPowerOfTwo ( string S ) { int N = S . Length ; Dictionary < char , int > freq = new Dictionary < char , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( freq . ContainsKey ( S [ i ] ) ) freq [ S [ i ] ] += 1 ; else freq [ S [ i ] ] = 1 ; } nearestPowerOfTwoUtil ( freq ) ; } public static void Main ( ) { string N = "16333331163" ; nearestPowerOfTwo ( N ) ; } }