Skip to content

Commit 80bce46

Browse files
committed
Fix zero input bug in binary_count_trailing_zeros
1 parent 841e947 commit 80bce46

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

bit_manipulation/binary_count_trailing_zeros.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
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+
Take in 1 integer, return the number of trailing zeros in binary representation.
87
98
>>> binary_count_trailing_zeros(25)
109
0
@@ -17,28 +16,39 @@ def binary_count_trailing_zeros(a: int) -> int:
1716
>>> binary_count_trailing_zeros(4294967296)
1817
32
1918
>>> binary_count_trailing_zeros(0)
20-
0
19+
Traceback (most recent call last):
20+
...
21+
ValueError: Trailing zeros for 0 are undefined
2122
>>> binary_count_trailing_zeros(-10)
2223
Traceback (most recent call last):
2324
...
2425
ValueError: Input value must be a positive integer
2526
>>> binary_count_trailing_zeros(0.8)
2627
Traceback (most recent call last):
2728
...
28-
TypeError: Input value must be a 'int' type
29+
TypeError: Input value must be an integer
2930
>>> binary_count_trailing_zeros("0")
3031
Traceback (most recent call last):
3132
...
32-
TypeError: '<' not supported between instances of 'str' and 'int'
33+
TypeError: Input value must be an integer
3334
"""
35+
36+
# Type check
37+
if not isinstance(a, int):
38+
raise TypeError("Input value must be an integer")
39+
40+
# Edge case: zero
41+
if a == 0:
42+
raise ValueError("Trailing zeros for 0 are undefined")
43+
44+
# Negative numbers not allowed
3445
if a < 0:
3546
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))
47+
48+
# Core logic
49+
return int(log2(a & -a))
3950

4051

4152
if __name__ == "__main__":
4253
import doctest
43-
44-
doctest.testmod()
54+
doctest.testmod()

0 commit comments

Comments
 (0)