![]() |
VOOZH | about |
Given an integer N, the task is to find the highest power of 2 that is smaller than or equal to N.
Examples:
Input: N = 9
Output: 8
Explanation:
Highest power of 2 less than 9 is 8.Input: N = -20
Output: -32
Explanation:
Highest power of 2 less than -20 is -32.Input: N = -84
Output: -128
Approach: The idea is to use logarithm to solve the above problem. For any given number N, it can be either positive or negative. The following task can be performed for each case:
Below is the implementation of the above approach:
-32
Time Complexity: O(log2(log2n))
Auxiliary Space: O(1)
Another Approach: we can use Bits manipulation in this way :
1.If number is positive- Then our answer will be pow(2,i) where i is leftmost set bit . Because if number is equal to pow(2,i), Then number is already power of 2, and if number > pow(2,i) , any power of 2 can not be greater than pow(2,i) as in bit concepts.
2.If number is negative- Let i is leftmost set bit .Then our answer will be pow(2,i) if(pow(2,i)==num). else our answer will be pow(2,i+1) because we are taking in negative.
Below is the implementation of the above approach:
-32
Time Complexity: O(log2n) , Because we are breaking loop , if leftmost set bit is found
Auxiliary Space: O(1)