Permutations of a given number that are a powers of 2
Input: S = “614”
All possible combinations of digit of S that are perfect power of 2 are 1, 4, 16, 64.
Input: S = “6”
Approach: The given problem can be solved by using Backtracking. The idea is to generate all possible permutations of the string S if it is a perfect power of 2 then print it. Follow the steps below to solve the problem:
- Define a function check(int number) to check if the given number is a power of 2 and perform the following tasks:
- If the number is equal to 0, then return false.
- If the Bitwise AND of number and number-1, then return true, else return false.
- Define a function calculate(int arr, string ans) and perform the following tasks:
- If the length of the string ans is not equal to 0 and the value of the function. check(Integer.parseInt(ans.trim())) returns true, then add this value to the HashSet H.
- Iterate over a range [0, 10] using the variable i and perform the following tasks:
- Initialize a HashSet H to store the possible string numbers which are a power of 2.
- Initialize an array, say temp to store the frequencies of the integers in the string str.
- Iterate in a while loop till N is not equal to 0 and perform the following steps:
- Initialize the variable rem as N%10 and increase the value of temp[rem] by 1.
- Divide the value of N by 10.
- Call the function calculate(temp, “”) to find the possible permutations of the string S.
- After performing the above steps, print the HashSet as the result.
Below is the implementation of the above approach.
4 [16, 64, 1, 4]
Time Complexity: O(N*9N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.