Given a positive integer n, compute floor(log2(n)) (the exponent of the highest power of two not exceeding n) without using a language built-in log2 function.
floor(log2(n)) is the number of times we can divide n by 2 (or shift right) before it becomes less than 1. Each division by 2 reduces the exponent by 1.
classSolution {
public:int floorLog2(int n) {
if (n <=0) return-1; // undefined for non-positive input
int ans =0;
while (n >1) {
n >>=1;
++ans;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
packagemainfuncfloorLog2(nint) int {
ifn<=0 {
return-1// undefined for non-positive }
ans:=0forn > 1 {
n>>=1ans++ }
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintfloorLog2(int n) {
if (n <= 0) return-1; // undefinedint ans = 0;
while (n > 1) {
n >>= 1;
ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
classSolution:
deffloorLog2(self, n: int) -> int:
if n <=0:
return-1 ans =0while n >1:
n >>=1 ans +=1return ans
If you repeatedly double a power-of-two value until it exceeds n, you can locate a bracket [2^k, 2^{k+1}) containing n. A small binary search between those exponents finds k = floor(log2(n)) in O(log k) steps. This is useful when bit-length operations are not available but you want fewer comparisons than repeated division in some contexts.