Nearest power of 2 of frequencies of each digit of a given number

• Last Updated : 12 May, 2021

Given a positive integer N, the task is to print the nearest power of 2 of the frequencies of each digit present in N. If there exists two nearest powers of 2 for any frequency, print the larger one.

Examples:

Input: N = 344422
Output:
2 -> 2
3 -> 1
4 -> 4
Explanation:
Frequency of the digit 3 is 1. Nearest power of 2 is 1.
Frequency of the digit 4 is 3. Nearest power of 2 is 4.
Frequency of the digit 2 is 2. Nearest power of 2 is 2.

Input: N = 16333331163
Output:
3 -> 8
1 -> 4
6 -> 2

Approach: The given problem can be solved using Hashing. Follow the steps below to solve the given problem:

Below is the implementation of the above approach:

C++

 // C++ program for the above approach #include using namespace std; // Function to find the nearest power of// 2 for all frequencies in the Map freqvoid nearestPowerOfTwoUtil(    unordered_map& freq){    // Traverse the Map    for (auto& it : freq) {         cout << it.first << " -> ";         // Calculate log of the        // current array element        int lg = log2(it.second);        int a = pow(2, lg);        int b = pow(2, lg + 1);         // Find the nearest power of 2        // for the current frequency        if ((it.second - a)            < (b - it.second)) {            cout << a << endl;        }        else {            cout << b << endl;        }    }} // Function to find nearest power of 2// for frequency of each digit of numvoid nearestPowerOfTwo(string& S){    // Length of string    int N = S.size();     // Stores the frequency of each    // character in the string    unordered_map freq;     // Traverse the string S    for (int i = 0; i < N; i++) {        freq[S[i]]++;    }     // Function call to generate    // nearest power of 2 for each    // frequency    nearestPowerOfTwoUtil(freq);} // Driver Codeint main(){    string N = "16333331163";    nearestPowerOfTwo(N);       return 0;}

Java

 // Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG {   // Function to find the nearest power of  // 2 for all frequencies in the Map freq  static void nearestPowerOfTwoUtil(HashMap freq)  {     // Traverse the Map    for (char key : freq.keySet())    {      System.out.print(key + " -> ");       // Calculate log of the      // current array element      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);       // Find the nearest power of 2      // for the current frequency      if ((freq.get(key) - a) < (b - freq.get(key))) {        System.out.println(a);      }      else {        System.out.println(b);      }    }  }   // Function to find nearest power of 2  // for frequency of each digit of num  static void nearestPowerOfTwo(String S)  {     // Length of string    int N = S.length();     // Stores the frequency of each    // character in the string    HashMap freq = new HashMap<>();     // Traverse the string S    for (int i = 0; i < N; i++)    {      freq.put(S.charAt(i), freq.getOrDefault(S.charAt(i), 0) + 1);    }     // Function call to generate    // nearest power of 2 for each    // frequency    nearestPowerOfTwoUtil(freq);  }   // Driver Code  public static void main(String[] args)  {     String N = "16333331163";    nearestPowerOfTwo(N);  }} // This code is contributed by Kingash.

Python3

 # Python3 program for the above approachfrom math import log2, pow # Function to find the nearest power of# 2 for all frequencies in the Map freqdef nearestPowerOfTwoUtil(freq):       # Traverse the Map    temp = {}    for key,value in freq.items():               # Calculate log of the        # current array element        lg = int(log2(value))        a  =  int(pow(2, lg))        b  =  int(pow(2, lg + 1))         # Find the nearest power of 2        # for the current frequency        if ((value - a) < (b - value)):            temp[(int(a))] = key        else:            temp[(int(b))] = key    for key,value in temp.items():        print(value,"->",key)         # Function to find nearest power of 2# for frequency of each digit of numdef nearestPowerOfTwo(S):       # Length of string    N = len(S)     # Stores the frequency of each    # character in the string    freq = {}     # Traverse the string S    for i in range(N):        if(S[i] in freq):            freq[S[i]] += 1        else:            freq[S[i]] = 1     # Function call to generate    # nearest power of 2 for each    # frequency    nearestPowerOfTwoUtil(freq) # Driver Codeif __name__ == '__main__':    N = "16333331163"    nearestPowerOfTwo(N)     # This code is contributed by bgangwar59.

C#

 // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the nearest power of// 2 for all frequencies in the Map freqstatic void nearestPowerOfTwoUtil(    Dictionary freq){     // Traverse the Map    foreach (KeyValuePair entry in freq)    {        char key = entry.Key;        Console.Write(key + " -> ");                 // Calculate log of the        // current array element        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);                 // Find the nearest power of 2        // for the current frequency        if ((freq[key] - a) < (b - freq[key]))        {            Console.Write(a + "\n");        }        else        {            Console.Write(b + "\n");        }    }} // Function to find nearest power of 2// for frequency of each digit of numstatic void nearestPowerOfTwo(string S){         // Length of string    int N = S.Length;         // Stores the frequency of each    // character in the string    Dictionary freq = new Dictionary();         // Traverse the string S    for(int i = 0; i < N; i++)    {        if (freq.ContainsKey(S[i]))            freq[S[i]] += 1;        else            freq[S[i]] = 1;    }         // Function call to generate    // nearest power of 2 for each    // frequency    nearestPowerOfTwoUtil(freq);} // Driver Codepublic static void Main(){    string N = "16333331163";         nearestPowerOfTwo(N);}} // This code is contributed by ipg2016107

Javascript


Output:
3 -> 8
1 -> 4
6 -> 2

Time Complexity: O(log10N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up