Skip to content

added binary_count_trailing_zeros.py #2557

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Nov 26, 2020
43 changes: 43 additions & 0 deletions bit_manipulation/binary_count_trailing_zeros.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from math import log2


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

>>> binary_count_trailing_zeros(25)
0
>>> binary_count_trailing_zeros(36)
2
>>> binary_count_trailing_zeros(16)
4
>>> binary_count_trailing_zeros(58)
1
>>> binary_count_trailing_zeros(4294967296)
32
>>> binary_count_trailing_zeros(0)
0
>>> binary_count_trailing_zeros(-10)
Traceback (most recent call last):
...
ValueError: the value of input must be positive
>>> binary_count_trailing_zeros(0.8)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for &: 'float' and 'float'
>>> binary_count_trailing_zeros("0")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if a < 0:
raise ValueError("the value of input must be positive")

return 0 if (a == 0) else int(log2(a & -a))


if __name__ == "__main__":
import doctest

doctest.testmod()