Skip to content

Commit a3bb227

Browse files
authored
Add function for highest set bit location
1 parent e2a83b3 commit a3bb227

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

bit_manipulation/highest_set_bit.py

Lines changed: 34 additions & 0 deletions
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.8)
14+
Traceback (most recent call last):
15+
...
16+
TypeError: Input value must be an 'int' type
17+
"""
18+
if not isinstance(number, int):
19+
raise TypeError("Input value must be an 'int' type")
20+
21+
position = 0
22+
while number:
23+
position += 1
24+
number >>= 1
25+
if number == 0:
26+
break
27+
28+
return position
29+
30+
31+
if __name__ == "__main__":
32+
import doctest
33+
34+
doctest.testmod()

0 commit comments

Comments
 (0)