Skip to content

Commit 11e6c6f

Browse files
Added algorithm for finding index of rightmost set bit (#7234)
* Added algorithm for finding index of rightmost set bit * applied suggested changes * applied suggested changes * Fixed failing Testcases * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 47100b9 commit 11e6c6f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/
2+
3+
4+
def get_index_of_rightmost_set_bit(number: int) -> int:
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 or not isinstance(number, int):
25+
raise ValueError("Input must be a non-negative integer")
26+
27+
intermediate = number & ~(number - 1)
28+
index = 0
29+
while intermediate:
30+
intermediate >>= 1
31+
index += 1
32+
return index - 1
33+
34+
35+
if __name__ == "__main__":
36+
"""
37+
Finding the index of rightmost set bit has some very peculiar use-cases,
38+
especially in finding missing or/and repeating numbers in a list of
39+
positive integers.
40+
"""
41+
import doctest
42+
43+
doctest.testmod(verbose=True)

0 commit comments

Comments
 (0)