Skip to content

Commit b46b92a

Browse files
authored
Add function for highest set bit location (TheAlgorithms#7586)
* Add function for highest set bit location * Address review comments
1 parent 74325d0 commit b46b92a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

bit_manipulation/highest_set_bit.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def get_highest_set_bit_position(number: int) -> int:
2+
"""
3+
Returns position of the highest set bit of a number.
4+
Ref - https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
5+
>>> get_highest_set_bit_position(25)
6+
5
7+
>>> get_highest_set_bit_position(37)
8+
6
9+
>>> get_highest_set_bit_position(1)
10+
1
11+
>>> get_highest_set_bit_position(4)
12+
3
13+
>>> get_highest_set_bit_position(0)
14+
0
15+
>>> get_highest_set_bit_position(0.8)
16+
Traceback (most recent call last):
17+
...
18+
TypeError: Input value must be an 'int' type
19+
"""
20+
if not isinstance(number, int):
21+
raise TypeError("Input value must be an 'int' type")
22+
23+
position = 0
24+
while number:
25+
position += 1
26+
number >>= 1
27+
28+
return position
29+
30+
31+
if __name__ == "__main__":
32+
import doctest
33+
34+
doctest.testmod()

0 commit comments

Comments
 (0)