From fcf063bf7645b6d6cf37270cea37b80dcf3aa294 Mon Sep 17 00:00:00 2001 From: Zendy <50132805+zendy199x@users.noreply.github.com> Date: Sun, 29 Mar 2026 14:26:14 +0700 Subject: [PATCH] refactor: off-by-one error in binary_count_trailing_zeros for zero input MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "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> --- bit_manipulation/binary_count_trailing_zeros.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/bit_manipulation/binary_count_trailing_zeros.py b/bit_manipulation/binary_count_trailing_zeros.py index f401c4ab9266..4075ff336c87 100644 --- a/bit_manipulation/binary_count_trailing_zeros.py +++ b/bit_manipulation/binary_count_trailing_zeros.py @@ -17,7 +17,9 @@ def binary_count_trailing_zeros(a: int) -> int: >>> binary_count_trailing_zeros(4294967296) 32 >>> binary_count_trailing_zeros(0) - 0 + Traceback (most recent call last): + ... + ValueError: Input value must be a positive integer >>> binary_count_trailing_zeros(-10) Traceback (most recent call last): ... @@ -31,11 +33,11 @@ def binary_count_trailing_zeros(a: int) -> int: ... TypeError: '<' not supported between instances of 'str' and 'int' """ - if a < 0: + if a <= 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") - return 0 if (a == 0) else int(log2(a & -a)) + return int(log2(a & -a)) if __name__ == "__main__":