Skip to content

Commit 953462c

Browse files
author
Anup Singh
committed
fix: off-by-one error in binary_count_trailing_zeros for zero input #14479
1 parent 791deb4 commit 953462c

1 file changed

Lines changed: 18 additions & 13 deletions

File tree

bit_manipulation/binary_count_trailing_zeros.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33

44
def binary_count_trailing_zeros(a: int) -> int:
55
"""
6-
Take in 1 integer, return a number that is
7-
the number of trailing zeros in binary representation of that number.
6+
Return the number of trailing zeros in the binary representation of a non-negative integer.
7+
8+
Note:
9+
For a == 0, returns 0 by convention.
810
911
>>> binary_count_trailing_zeros(25)
1012
0
@@ -21,24 +23,27 @@ def binary_count_trailing_zeros(a: int) -> int:
2123
>>> binary_count_trailing_zeros(-10)
2224
Traceback (most recent call last):
2325
...
24-
ValueError: Input value must be a positive integer
26+
ValueError: Input must be a non-negative integer
2527
>>> binary_count_trailing_zeros(0.8)
2628
Traceback (most recent call last):
2729
...
28-
TypeError: Input value must be a 'int' type
30+
TypeError: Input must be an integer
2931
>>> binary_count_trailing_zeros("0")
3032
Traceback (most recent call last):
3133
...
32-
TypeError: '<' not supported between instances of 'str' and 'int'
34+
TypeError: Input must be an integer
3335
"""
34-
if a < 0:
35-
raise ValueError("Input value must be a positive integer")
36-
elif isinstance(a, float):
37-
raise TypeError("Input value must be a 'int' type")
38-
return 0 if (a == 0) else int(log2(a & -a))
3936

37+
38+
if not isinstance(a, int):
39+
raise TypeError("Input must be an integer")
40+
41+
42+
if a < 0:
43+
raise ValueError("Input must be a non-negative integer")
4044

41-
if __name__ == "__main__":
42-
import doctest
45+
46+
if a == 0:
47+
return 0
4348

44-
doctest.testmod()
49+
return int(log2(a & -a))

0 commit comments

Comments
 (0)