VOOZH about

URL: https://www.geeksforgeeks.org/dsa/highest-power-of-2-less-than-or-equal-to-given-integer/

⇱ Highest power of 2 less than or equal to given Integer - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Highest power of 2 less than or equal to given Integer

Last Updated : 12 Jul, 2025

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:
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:  

  1. If the input is positive: floor(log2(N)) can be calculated.
  2. If the input is negative: ceil(log2(N)) can be calculated and a -ve sign can be added to the value.

Below is the implementation of the above approach:  


Output
-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:  


Output
-32

Time Complexity: O(log2n) , Because we are breaking loop , if leftmost set bit is found
Auxiliary Space: O(1)

Comment
Article Tags: