![]() |
VOOZH | about |
Given a number n, find the highest power of 2 that is smaller than or equal to n.
Examples :
Input : n = 10 Output : 8 Input : n = 19 Output : 16 Input : n = 32 Output : 32
A simple solution is to start checking from n and keep decrementing until we find a power of 2.
8
Time complexity : O(n). In worst case, the loop runs floor(n/2) times. The worst case happens when n is of the form 2x - 1.
Auxiliary Space : O(1) since only constant space is used for variables
An efficient solution is to use bitwise left shift operator to find all powers of 2 starting from 1. For every power check if it is smaller than or equal to n or not. Below is the implementation of the idea.
8
Time Complexity: O(32)
Auxiliary Space: O(1)
A Solution using Log(n)
Thanks to Anshuman Jha for suggesting this solution.
8
Time Complexity: O(logn)
Auxiliary Space: O(1)
Solution using bitmasks :
8
Time Complexity: O(1)
Auxiliary Space: O(1) since only constant space is used for variables
A solution using MSB
If the given number is the power of two then it is the required number otherwise set only the most significant bit which gives us the required number.
4
Time Complexity : O(1) as counting leading zeroes can cause at most O(64) time complexity.
Auxiliary Space: O(1)
Application Problem:
Some people are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person in the original queue.
Print the position(original queue) of that person who is left.
Examples :
Input: n = 10 Output:8 Explanation : 1 2 3 4 5 6 7 8 9 10 ===>Given queue 2 4 6 8 10 4 8 8 Input: n = 17 Input: 16 Explanation : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ===>Given queue 2 4 6 8 10 12 14 16 4 8 12 16 8 16 16
Related Article :
Power of 2 greater than or equal to a given number.