Skip to content

Commit fcf063b

Browse files
committed
refactor: off-by-one error in binary_count_trailing_zeros for zero input
"The function returns `0` for `a == 0`, but mathematically, trailing zeros in binary representation of 0 are undefined (or conventionally treated as infinite). While `log2(a & -a)` fails for `a=0`, the current fallback to `0` is inconsistent with the documented behavior: `binary_count_trailing_zeros(16)` returns `4`, but `0` has infinitely many trailing zeros — returning `0` is misleading and could cause bugs in algorithms relying on this (e.g., bit manipulation loops expecting correct trailing zero counts)." Signed-off-by: Zendy <50132805+zendy199x@users.noreply.github.com>
1 parent 841e947 commit fcf063b

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

bit_manipulation/binary_count_trailing_zeros.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ def binary_count_trailing_zeros(a: int) -> int:
1717
>>> binary_count_trailing_zeros(4294967296)
1818
32
1919
>>> binary_count_trailing_zeros(0)
20-
0
20+
Traceback (most recent call last):
21+
...
22+
ValueError: Input value must be a positive integer
2123
>>> binary_count_trailing_zeros(-10)
2224
Traceback (most recent call last):
2325
...
@@ -31,11 +33,11 @@ def binary_count_trailing_zeros(a: int) -> int:
3133
...
3234
TypeError: '<' not supported between instances of 'str' and 'int'
3335
"""
34-
if a < 0:
36+
if a <= 0:
3537
raise ValueError("Input value must be a positive integer")
3638
elif isinstance(a, float):
3739
raise TypeError("Input value must be a 'int' type")
38-
return 0 if (a == 0) else int(log2(a & -a))
40+
return int(log2(a & -a))
3941

4042

4143
if __name__ == "__main__":

0 commit comments

Comments
 (0)