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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestPowerOfTwoUtil ( unordered_map < char , int > & freq ) { for ( auto & it : freq ) { cout << it . first << " ▁ - > ▁ " ; int lg = log2 ( it . second ) ; int a = pow ( 2 , lg ) ; int b = pow ( 2 , lg + 1 ) ; if ( ( it . second - a ) < ( b - it . second ) ) { cout << a << endl ; } else { cout << b << endl ; } } } void nearestPowerOfTwo ( string & S ) { int N = S . size ( ) ; unordered_map < char , int > freq ; for ( int i = 0 ; i < N ; i ++ ) { freq [ S [ i ] ] ++ ; } nearestPowerOfTwoUtil ( freq ) ; } int main ( ) { string N = "16333331163" ; nearestPowerOfTwo ( N ) ; return 0 ; }