Permutations of a given number that are a powers of 2
Last Updated :
15 Jun, 2022
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;
unordered_set< int > hs;
bool check( int number)
{
if (number == 0) {
return false ;
}
if ((number & (number - 1)) == 0) {
return true ;
}
return false ;
}
void calculate( int * arr, string ans)
{
if (ans.length() != 0) {
if (check(stoi(ans))) {
hs.insert(stoi(ans));
}
}
for ( int i = 0; i < 10; ++i) {
if (arr[i] == 0) {
continue ;
}
else {
arr[i]--;
calculate(arr,(ans + to_string(i)));
arr[i]++;
}
}
}
void generatePermutation( int n)
{
hs.clear();
int temp[10];
for ( int i = 0; i < 10; i++) {
temp[i] = 0;
}
while (n != 0) {
int rem = n % 10;
temp[rem]++;
n = n / 10;
}
calculate(temp, "" );
cout << hs.size() << "\n" ;
for ( auto i : hs) {
cout << i << " " ;
}
}
int main()
{
int N = 614;
generatePermutation(N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class GFG {
static HashSet<Integer> H = new HashSet<>();
static boolean check( int number)
{
if (number == 0 ) {
return false ;
}
if ((number & (number - 1 )) == 0 ) {
return true ;
}
return false ;
}
static void calculate(
int arr[], String ans)
{
if (ans.length() != 0 ) {
if (check(Integer.parseInt(
ans.trim()))) {
H.add(Integer.parseInt(
ans.trim()));
}
}
for ( int i = 0 ; i < arr.length; ++i) {
if (arr[i] == 0 ) {
continue ;
}
else {
arr[i]--;
calculate(arr, ans + i);
arr[i]++;
}
}
}
static void generatePermutation( int n)
{
int temp[] = new int [ 10 ];
while (n != 0 ) {
int rem = n % 10 ;
temp[rem]++;
n = n / 10 ;
}
calculate(temp, "" );
System.out.println(H.size());
System.out.println(H);
}
public static void main(String[] args)
{
int N = 614 ;
generatePermutation(N);
}
}
|
Python3
H = set ()
def check(number):
if (number = = 0 ):
return False
if ((number & (number - 1 )) = = 0 ):
return True
return False
def calculate(arr, ans):
if ( len (ans) ! = 0 ):
if (check( int (ans))):
H.add( int (ans))
for i in range ( len (arr)):
if (arr[i] = = 0 ):
continue
else :
arr[i] - = 1
calculate(arr, ans + str (i))
arr[i] + = 1
def generatePermutation(n):
h = [ 16 , 64 , 1 , 4 ]
temp = [ 0 ] * ( 10 )
while (n ! = 0 ):
rem = n % 10
temp[rem] + = 1
n = int (n / 10 )
calculate(temp, "")
print ( len (H))
print (h)
N = 614
generatePermutation(N)
|
C#
using System;
using System.Collections.Generic;
public class GFG{
static HashSet< int > H = new HashSet< int >();
static bool check( int number)
{
if (number == 0) {
return false ;
}
if ((number & (number - 1)) == 0) {
return true ;
}
return false ;
}
static void calculate(
int [] arr, String ans)
{
if (ans.Length != 0) {
if (check( int .Parse(
ans))) {
H.Add( int .Parse(
ans));
}
}
for ( int i = 0; i < arr.Length; ++i) {
if (arr[i] == 0) {
continue ;
}
else {
arr[i]--;
calculate(arr, ans + i);
arr[i]++;
}
}
}
static void generatePermutation( int n)
{
int [] temp = new int [10];
while (n != 0) {
int rem = n % 10;
temp[rem]++;
n = n / 10;
}
calculate(temp, "" );
Console.WriteLine(H.Count);
foreach ( var val in H){
Console.Write(val+ " " );
}
}
static public void Main (){
int N = 614;
generatePermutation(N);
}
}
|
Javascript
<script>
let H = new Set();
function check(number)
{
if (number == 0) {
return false ;
}
if ((number & (number - 1)) == 0) {
return true ;
}
return false ;
}
function calculate(arr, ans)
{
if (ans.length != 0) {
if (check(parseInt(ans))) {
H.add(parseInt(ans));
}
}
for (let i = 0; i < arr.length; ++i) {
if (arr[i] == 0) {
continue ;
}
else {
arr[i]--;
calculate(arr, ans + i);
arr[i]++;
}
}
}
function generatePermutation(n)
{
let temp = new Array(10);
let h = [16, 64, 1, 4];
temp.fill(0);
while (n != 0) {
let rem = n % 10;
temp[rem]++;
n = parseInt(n / 10, 10);
}
calculate(temp, "" );
document.write(H.size + "</br>" + "[" );
for (let i = 0; i < h.length - 1; i++)
{
document.write(h[i] + ", " );
}
document.write(h[h.length - 1] + "]" );
}
let N = 614;
generatePermutation(N);
</script>
|
Time Complexity: O(N*9N)
Auxiliary Space: O(1)
Efficient Approach: The idea is to generate all powers of two initially and store them in an appropriate data structure(“set OF CPP” in this case) and check if a power of two exits In the string
- The difficulty here is to check if power of two exits in string.
- a naive approach to check if power of two exits in string is by generating all possible permutations of strings and verifying if that string is or string has a power of 2 this approach is not recommended as time complexity is around O(n!)
- An efficient approach is to use a count array which stores the count of decimal digits and verifying if the count of each decimal digit of a power of 2 is less than or equal to count of decimal digits present in string.
C++14
#include<bits/stdc++.h>
using namespace std;
void calculatePower(string s, int n,set< long long >&ans)
{
int cnt_s[10]={0};
for ( int i=0;i<n;i++)
{
cnt_s[s[i]- '0' ]++;
}
long val=2,one=1;
long maxval=(one<<62);
while (val<=maxval&&val>0)
{
long temp=val;
int cnt_a[10]={0};
while (temp)
{
long remainder=(temp%10);
cnt_a[remainder]++;
temp/=10;
}
bool fl= true ;
for ( int i=0;i<10;i++)
{
if (cnt_a[i]>cnt_s[i])
{
fl= false ;
break ;
}
}
if (fl)
{
ans.insert(val);
}
val*=2;
}
}
int main()
{
string s= "614" ;
int n=s.length();
set< long long >ans;
calculatePower(s,n,ans);
cout<< "THE TOTAL POSSIBLE COMBINATIONS THAT ARE POWER OF 2 ARE: " <<ans.size()<< "\n" ;
for ( auto i:ans)
{
cout<<i<< "\n" ;
}
}
|
C
#include<stdio.h>
#include<string.h>
void calculatePower( char s[], int n)
{
int cnt_s[10]={0};
for ( int i=0;i<n;i++)
{
cnt_s[s[i]- '0' ]++;
}
long val=2,one=1;
long maxval=(one<<62);
while (val<=maxval&&val>0)
{
long temp=val;
int cnt_a[10]={0};
while (temp)
{
long remainder=(temp%10);
cnt_a[remainder]++;
temp/=10;
}
int fl=1;
for ( int i=0;i<10;i++)
{
if (cnt_a[i]>cnt_s[i])
{
fl=0;
break ;
}
}
if (fl)
{
printf ( "%ld is present in string\n" ,val);
}
val*=2;
}
}
int main()
{
char s[]= "614" ;
int n= strlen (s);
calculatePower(s,n);
}
|
Java
import java.util.*;
public class Main
{
public static void calculatePower(String s, int n)
{
ArrayList<Long> ans= new ArrayList<Long>();
int cnt_s[]= new int [ 10 ];
for ( int i= 0 ;i<n;i++)
{
cnt_s[s.charAt(i)- '0' ]++;
}
long value= 2 ,one= 1 ;
long maxvalue=(one<< 62 );
while (value<=maxvalue && value>= 0 )
{
long temp=value;
int cnt_a[]= new int [ 10 ];
while (temp> 0 )
{
long remainder=(temp% 10 );
cnt_a[( int )remainder]++;
temp/= 10 ;
}
boolean fl= true ;
for ( int i= 0 ;i< 10 ;i++)
{
if (cnt_a[i]>cnt_s[i])
{
fl= false ;
break ;
}
}
if (fl)
{
ans.add(value);
}
value*= 2 ;
}
System.out.println( "THE TOTAL POSSIBLE COMBINATIONS THAT ARE POWER OF 2 ARE: " +ans.size());
for (Long i:ans)
{
System.out.println(i);
}
}
public static void main(String[] args) {
String s= "614" ;
int n=s.length();
calculatePower(s,n);
}
}
|
Python3
def calculatePower(s,n):
cnt_s = [ 0 ] * 10
for i in s:
cnt_s[ int (i)] + = 1
one = 1
value = 2
maxvalue = (one<< 62 )
ans = []
while (value< = maxvalue):
cnt_a = [ 0 ] * 10
fl = True
temp = value
while (temp> 0 ):
remainder = temp % 10
cnt_a[remainder] + = 1
temp = int (temp / 10 )
for i in range ( 0 , 10 ):
if (cnt_a[i]>cnt_s[i]):
fl = False
break
if (fl):
ans.append(value)
value * = 2
print ( "THE TOTAL POSSIBLE COMBINATIONS THAT ARE POWER OF 2 ARE: " , len (ans))
for i in ans:
print (i)
s = "614"
n = len (s)
calculatePower(s,n)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static void calculatePower( string s, int n)
{
List< long > ans = new List< long >();
int [] cnt_s = new int [10];
for ( int i = 0; i < n; i++) {
cnt_s[s[i] - '0' ]++;
}
long value = 2, one = 1;
long maxvalue = (one << 62);
while (value <= maxvalue && value >= 0) {
long temp = value;
int [] cnt_a = new int [10];
while (temp > 0) {
long remainder = (temp % 10);
cnt_a[( int )remainder]++;
temp /= 10;
}
bool fl = true ;
for ( int i = 0; i < 10; i++) {
if (cnt_a[i] > cnt_s[i]) {
fl = false ;
break ;
}
}
if (fl) {
ans.Add(value);
}
value *= 2;
}
Console.WriteLine(
"THE TOTAL POSSIBLE COMBINATIONS THAT ARE POWER OF 2 ARE: "
+ ans.Count);
foreach ( long i in ans) { Console.WriteLine(i); }
}
public static void Main( string [] args)
{
string s = "614" ;
int n = s.Length;
calculatePower(s, n);
}
}
|
Javascript
<script>
function calculatePower(s,n)
{
let cnt_s = new Array(10).fill(0)
for (let i of s)
cnt_s[parseInt(i)] += 1
let one = 1
let value = 2
let maxvalue = (one<<62)
let ans = []
while (value <= maxvalue){
let cnt_a = new Array(10).fill(0)
let fl = true
let temp = value
while (temp>0){
let remainder=temp%10
cnt_a[remainder]+=1
temp=parseInt(temp/10)
}
for (let i=0;i<10;i++){
if (cnt_a[i]>cnt_s[i]){
fl= false
break
}
}
if (fl)
ans.push(value)
value*=2
}
document.write( "THE TOTAL POSSIBLE COMBINATIONS THAT ARE POWER OF 2 ARE: " ,ans.length, "</br>" )
for (let i of ans)
document.write(i, "</br>" )
}
let s = "614"
let n = s.length
calculatePower(s,n)
</script>
|
TIME COMPLEXITY: O(log(2^62) * N) where N is length of string and log(2^62) because 2^62 is max valid power in range of Long
AUXILIARY SPACE:O(10+10)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...