Skip to content

Commit 98c7772

Browse files
Added algorithm for finding index of rightmost set bit
1 parent 98a4c24 commit 98c7772

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/"
2+
3+
def get_index_of_rightmost_set_bit(number: int) -> int:
4+
5+
"""
6+
Take in a positive integer 'number'.
7+
Returns the zero-based index of first set bit in that 'number' from right.
8+
Returns -1, If no set bit found.
9+
10+
>>> get_index_of_rightmost_set_bit(0)
11+
-1
12+
>>> get_index_of_rightmost_set_bit(5)
13+
0
14+
>>> get_index_of_rightmost_set_bit(36)
15+
2
16+
>>> get_index_of_rightmost_set_bit(8)
17+
3
18+
>>> get_index_of_rightmost_set_bit(-18)
19+
Traceback (most recent call last):
20+
...
21+
ValueError: Input must be a non-negative integer
22+
"""
23+
24+
if number>=0 and type(number)==int:
25+
intermediate = number&~(number-1)
26+
index = 0
27+
while intermediate:
28+
intermediate>>=1
29+
index+=1
30+
return index-1
31+
else: raise ValueError("Input must be a non-negative integer")
32+
33+
"""
34+
Finding the index of rightmost set bit has some very peculiar use-cases,
35+
especially in finding missing or/and repeating numbers in a list of positive integers.
36+
"""
37+
38+
if __name__ == "__main__":
39+
import doctest
40+
41+
doctest.testmod()

0 commit comments

Comments
 (0)