![]() |
VOOZH | about |
Given a positive number N, the task is to find out all the perfect powers of two which are less than or equal to the given number N.
Examples:
Input: N = 63
Output: 32 16 8 4 2 1
Explanation: There are total of 6 powers of 2, which are less than or equal to the given number N.Input: N = 193
Output: 128 64 32 16 8 4 2 1
Explanation: There are total of 8 powers of 2, which are less than or equal to the given number N.
Naive Approach: The idea is to traverse each number from N to 1 and check if it is a perfect power of 2 or not. If yes, then print that number.
Another Approach: The idea is to find all powers of 2 and simply print the powers that are lesser than or equal to N.
Another Approach: The idea is based on the concept that all powers of 2 has all bits set, in its binary form. Bitset function is used in this approach solve the above problem.
Below are the steps:
Below is the implementation of the above approach:
32 16 8 4 2 1
Time Complexity: O(log N)
Auxiliary Space: O(1)