Skip to content
Related Articles

Related Articles

Improve Article

Permutations of a given number that are a powers of 2

  • Difficulty Level : Hard
  • Last Updated : 10 Aug, 2021

Given a string S consisting of N digits, the task is to print all possible combinations of the digits of the S that is a perfect power of 2.

Examples:

Input: S = “614”
Output: 4
Explanation:
All possible combinations of digit of S that are perfect power of 2 are 1, 4, 16, 64.

Input: S = “6”
Output: 0

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:
      • If arr[i] is equal to 0, then continue.
      • Else, decrease the value of arr[i] by 1 and call the function calculate(temp, “”) to find the other possible permutations of the string str and add the value of arr[i] by 1.
  • 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.

C++




#include <bits/stdc++.h>
using namespace std;
 
// Stores the all possible generated
// integers from the given string
unordered_set<int> hs;
 
// Function to check if the
// number is power of 2
bool check(int number)
{
    // If number is 0, then it
    // can't be a power of 2
    if (number == 0) {
        return false;
    }
 
    // If the bitwise AND of n
    // and n-1 is 0, then only
    // it is a power of 2
    if ((number & (number - 1)) == 0) {
        return true;
    }
 
    return false;
}
 
// Function to generate the numbers
void calculate(int* arr, string ans)
{
 
    if (ans.length() != 0) {
 
        // Checking the number
        if (check(stoi(ans))) {
            hs.insert(stoi(ans));
        }
    }
 
    // Iterate over the range
    for (int i = 0; i < 10; ++i) {
 
        if (arr[i] == 0) {
            continue;
        }
 
        else {
 
            // Use the number
            arr[i]--;
            calculate(arr,(ans +  to_string(i)));
 
            // Bactracking Step
            arr[i]++;
        }
    }
}
 
// Function to find the all possible
// permutations
void generatePermutation(int n)
{
    hs.clear();
    // Stores the frequency of digits
    int temp[10];
    for (int i = 0; i < 10; i++) {
        temp[i] = 0;
    }
 
    // Iterate over the number
    while (n != 0) {
        int rem = n % 10;
        temp[rem]++;
        n = n / 10;
    }
 
    // Function Call
    calculate(temp, "");
 
    // Print the result
    cout << hs.size() << "\n";
    for (auto i : hs) {
        cout << i << " ";
    }
}
 
int main()
{
 
    int N = 614;
    generatePermutation(N);
    return 0;
}

Java




// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
public class GFG {
 
    // Stores the all possible generated
    // integers from the given string
    static HashSet<Integer> H = new HashSet<>();
 
    // Function to check if the
    // number is power of 2
    static boolean check(int number)
    {
        // If number is 0, then it
        // can't be a power of 2
        if (number == 0) {
            return false;
        }
 
        // If the bitwise AND of n
        // and n-1 is 0, then only
        // it is a power of 2
        if ((number & (number - 1)) == 0) {
            return true;
        }
 
        return false;
    }
 
    // Function to generate the numbers
    static void calculate(
        int arr[], String ans)
    {
 
        if (ans.length() != 0) {
 
            // Checking the number
            if (check(Integer.parseInt(
                    ans.trim()))) {
                H.add(Integer.parseInt(
                    ans.trim()));
            }
        }
 
        // Iterate over the range
        for (int i = 0; i < arr.length; ++i) {
 
            if (arr[i] == 0) {
                continue;
            }
 
            else {
 
                // Use the number
                arr[i]--;
                calculate(arr, ans + i);
 
                // Bactracking Step
                arr[i]++;
            }
        }
    }
 
    // Function to find the all possible
    // permutations
    static void generatePermutation(int n)
    {
        // Stores the frequency of digits
        int temp[] = new int[10];
 
        // Iterate over the number
        while (n != 0) {
            int rem = n % 10;
            temp[rem]++;
            n = n / 10;
        }
 
        // Function Call
        calculate(temp, "");
 
        // Print the result
        System.out.println(H.size());
        System.out.println(H);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 614;
        generatePermutation(N);
    }
}

C#




using System;
using System.Collections.Generic;
public class GFG{
 
  // Stores the all possible generated
    // integers from the given string
    static HashSet<int> H = new HashSet<int>();
 
    // Function to check if the
    // number is power of 2
    static bool check(int number)
    {
        // If number is 0, then it
        // can't be a power of 2
        if (number == 0) {
            return false;
        }
 
        // If the bitwise AND of n
        // and n-1 is 0, then only
        // it is a power of 2
        if ((number & (number - 1)) == 0) {
            return true;
        }
 
        return false;
    }
 
    // Function to generate the numbers
    static void calculate(
        int[] arr, String ans)
    {
 
        if (ans.Length != 0) {
 
            // Checking the number
            if (check(int.Parse(
                    ans))) {
                H.Add(int.Parse(
                    ans));
            }
        }
 
        // Iterate over the range
        for (int i = 0; i < arr.Length; ++i) {
 
            if (arr[i] == 0) {
                continue;
            }
 
            else {
 
                // Use the number
                arr[i]--;
                calculate(arr, ans + i);
 
                // Bactracking Step
                arr[i]++;
            }
        }
    }
 
    // Function to find the all possible
    // permutations
    static void generatePermutation(int n)
    {
        // Stores the frequency of digits
        int[] temp = new int[10];
 
        // Iterate over the number
        while (n != 0) {
            int rem = n % 10;
            temp[rem]++;
            n = n / 10;
        }
 
        // Function Call
        calculate(temp, "");
 
        // Print the result
        Console.WriteLine(H.Count);
      foreach(var val in H){
        Console.Write(val+" ");
      }
    }
    static public void Main (){
 
      int N = 614;
      generatePermutation(N);
    }
}
 
// This code is contributed by maddler.
Output: 
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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :