![]() |
VOOZH | about |
Given a number, find the greatest number less than the given a number which is the power of two or find the most significant bit number .
Examples:
Input: 10
Output: 8
Explanation:
Greatest number which is a Power of 2 less than 10 is 8
Binary representation of 10 is 1010
The most significant bit corresponds to decimal number 8.Input: 18
Output: 16
A simple solution is to one by one divide n by 2 until it becomes 0 and increment a count while doing this. This count actually represents the position of MSB.
0 1
Time Complexity: O(logn)
Auxiliary Space: O(1)
An efficient solution for a fixed size integer (say 32 bits) is to one by one set bits, then add 1 so that only the bit after MSB is set. Finally right shift by 1 and return the answer. This solution does not require any condition checking.
256 2147483648
Time Complexity: O(1)
Auxiliary Space: O(1)
Using __builtin_clz(x) (GCC builtin function)
Say for a fixed integer (32 bits), count the number of leading zeroes by using the built-in function and subtract it from 31 to get the position of MSB from left, then return the MSB using left shift operation on 1.
An efficient solution for a fixed size integer (say 32 bits) is to one by one set bits, then add 1 so that only the bit after MSB is set. Finally right shift by 1 and return the answer. This solution does not require any condition checking.
256 2147483648
Time Complexity: O(1)
Auxiliary Space: O(1)
Another Approach: Given a number n. First, find the position of the most significant set bit and then compute the value of the number with a set bit at k-th position.
Thanks Rohit Narayan for suggesting this method.
256
Time Complexity: O(logn)
Auxiliary Space: O(1)