File tree 1 file changed +14
-11
lines changed
1 file changed +14
-11
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
"""
6
7
Take in a positive integer 'number'.
7
8
Returns the zero-based index of first set bit in that 'number' from right.
8
9
Returns -1, If no set bit found.
9
10
10
- >>> get_index_of_rightmost_set_bit(0)
11
+ >>> get_index_of_rightmost_set_bit(0)
11
12
-1
12
- >>> get_index_of_rightmost_set_bit(5)
13
+ >>> get_index_of_rightmost_set_bit(5)
13
14
0
14
- >>> get_index_of_rightmost_set_bit(36)
15
+ >>> get_index_of_rightmost_set_bit(36)
15
16
2
16
- >>> get_index_of_rightmost_set_bit(8)
17
+ >>> get_index_of_rightmost_set_bit(8)
17
18
3
18
- >>> get_index_of_rightmost_set_bit(-18)
19
+ >>> get_index_of_rightmost_set_bit(-18)
19
20
Traceback (most recent call last):
20
21
...
21
22
ValueError: Input must be a non-negative integer
22
23
"""
23
24
24
- if number >= 0 and type (number )== int :
25
- intermediate = number & ~ (number - 1 )
25
+ if number >= 0 and type (number ) == int :
26
+ intermediate = number & ~ (number - 1 )
26
27
index = 0
27
28
while intermediate :
28
- intermediate >>= 1
29
- index += 1
30
- return index - 1
31
- else : raise ValueError ("Input must be a non-negative integer" )
29
+ intermediate >>= 1
30
+ index += 1
31
+ return index - 1
32
+ else :
33
+ raise ValueError ("Input must be a non-negative integer" )
34
+
32
35
33
36
"""
34
37
Finding the index of rightmost set bit has some very peculiar use-cases,
You can’t perform that action at this time.
0 commit comments