Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix zero input bug in binary_count_trailing_zeros
  • Loading branch information
satwik-exe committed Apr 1, 2026
commit 80bce46523129f7409c1b3f1fc34c25ed4532ca0
30 changes: 20 additions & 10 deletions bit_manipulation/binary_count_trailing_zeros.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@

def binary_count_trailing_zeros(a: int) -> int:
"""
Take in 1 integer, return a number that is
the number of trailing zeros in binary representation of that number.
Take in 1 integer, return the number of trailing zeros in binary representation.

>>> binary_count_trailing_zeros(25)
0
Expand All @@ -17,28 +16,39 @@
>>> binary_count_trailing_zeros(4294967296)
32
>>> binary_count_trailing_zeros(0)
0
Traceback (most recent call last):
...
ValueError: Trailing zeros for 0 are undefined
>>> binary_count_trailing_zeros(-10)
Traceback (most recent call last):
...
ValueError: Input value must be a positive integer
>>> binary_count_trailing_zeros(0.8)
Traceback (most recent call last):
...
TypeError: Input value must be a 'int' type
TypeError: Input value must be an integer
>>> binary_count_trailing_zeros("0")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
TypeError: Input value must be an integer
"""

# Type check
if not isinstance(a, int):
raise TypeError("Input value must be an integer")

# Edge case: zero
if a == 0:
raise ValueError("Trailing zeros for 0 are undefined")

# Negative numbers not allowed
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))

# Core logic
return int(log2(a & -a))


if __name__ == "__main__":
import doctest

doctest.testmod()
doctest.testmod()

Check failure on line 54 in bit_manipulation/binary_count_trailing_zeros.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (W292)

bit_manipulation/binary_count_trailing_zeros.py:54:22: W292 No newline at end of file help: Add trailing newline
Loading