File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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 ()
You can’t perform that action at this time.
0 commit comments