Problem of the day
You are given an integer ‘N’. We can reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true if and only if we can do this so that the resulting number is a power of two. Else, return false.
For Example :
Given :-
‘N’ = 218
Then the answer will be true because it can be rearranged to 128, which is 2 raised to the power of 7.
Input Format :
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘T’ lines of the test case contain exactly one integer, ‘N’ the number given to us.
Output Format :
For each test case, print 1 or 0 depicting if it is possible or impossible to rearrange the given number as a power of 2, respectively.
The output of each test case will be printed in a separate line.
Note :
You don't have to print anything; It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
0 <= N <= 10 ^ 9
Time limit: 1 sec
2
100
218
0
1
For the first test case :
All the possible combinations of 100 start with 0, which is not allowed, and the only permutation where it starts with 1 is 100, which is not a power of 2. Therefore, the answer is false.
For the second test case :
Then the answer will be true because it can be rearranged to 128, which is 2 raised to the power of 7.
2
46
1
1
1
Can we try all permutations?
The main idea is to convert ‘N’ to a string ‘S’ and sort its characters. Then for all possible permutations, check if the current permutation is a power of 2.
O(log(N)!), where N is the number given.
For a given number N, it contains log(N) digits, and we are trying all possible permutations, therefore log(N)! permutations exist. Therefore the net time complexity is O(log(N)!).
O(log(N)), where N is the number given.
Since we are using a string to store the number and contains at max log(N) digits.