File tree 1 file changed +11
-9
lines changed
1 file changed +11
-9
lines changed Original file line number Diff line number Diff line change 1
1
# Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/
2
2
3
+
3
4
def get_index_of_rightmost_set_bit (number : int ) -> int :
4
5
"""
5
6
Take in a positive integer 'number'.
6
7
Returns the zero-based index of first set bit in that 'number' from right.
7
8
Returns -1, If no set bit found.
8
9
9
- >>> get_index_of_rightmost_set_bit(0)
10
+ >>> get_index_of_rightmost_set_bit(0)
10
11
-1
11
- >>> get_index_of_rightmost_set_bit(5)
12
+ >>> get_index_of_rightmost_set_bit(5)
12
13
0
13
- >>> get_index_of_rightmost_set_bit(36)
14
+ >>> get_index_of_rightmost_set_bit(36)
14
15
2
15
- >>> get_index_of_rightmost_set_bit(8)
16
+ >>> get_index_of_rightmost_set_bit(8)
16
17
3
17
- >>> get_index_of_rightmost_set_bit(-18)
18
+ >>> get_index_of_rightmost_set_bit(-18)
18
19
Traceback (most recent call last):
19
20
...
20
21
ValueError: Input must be a non-negative integer
@@ -23,12 +24,13 @@ def get_index_of_rightmost_set_bit(number: int) -> int:
23
24
if 0 > number and not isinstance (number , int ):
24
25
raise ValueError ("Input must be a non-negative integer" )
25
26
26
- intermediate = number & ~ (number - 1 )
27
+ intermediate = number & ~ (number - 1 )
27
28
index = 0
28
29
while intermediate :
29
- intermediate >>= 1
30
- index += 1
31
- return index - 1
30
+ intermediate >>= 1
31
+ index += 1
32
+ return index - 1
33
+
32
34
33
35
if __name__ == "__main__" :
34
36
"""
You can’t perform that action at this time.
0 commit comments