Given a number n
, find the highest power of 2 that is smaller than or equal to n
.
Example 1:
Example 2:
Example 3:
The simplest solution is to start with powers of 2
from 1, such as 21. For every power of two, check if it’s greater than the given number. If it’s greater than the given number, then return the previous/last power of two.
class Main{static int highestPowerofTwoLessThanN(int n) {if (n < 1) return 0;int pow = 1;while((1 << pow) <= n) pow++;return (1 << (pow - 1));}public static void main (String[] args) {int n = 10;System.out.println("The highest power of 2 less than " + n + " is " + highestPowerofTwoLessThanN(n));}}
n
is less than 1
, then return zero.power
variable to 1
.n
, increment the power value by 1
.while
loop, it means that we have a power of two that is greater than n
. Hence, we return the power of two for the last/previous power value.n
number is defined.Time Complexity: O(n) in worst case
Space Complexity: O(1)
Free Resources