Skip to content

add count_number_of_one_bits.py #4195

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 2 commits into from
Feb 12, 2021
Merged
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
48 changes: 48 additions & 0 deletions bit_manipulation/count_number_of_one_bits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
def count_one_bits(number: int) -> int:
"""
Take in an 32 bit integer, count the number of one bits,
return the number of one bits
result of a count_one_bits and operation on the integer provided.
>>> count_one_bits(25)
3
>>> count_one_bits(37)
3
>>> count_one_bits(21)
3
>>> count_one_bits(58)
4
>>> count_one_bits(0)
0
>>> count_one_bits(256)
1
>>> count_one_bits(-1)
Traceback (most recent call last):
...
ValueError: the value of input must be positive
>>> count_one_bits(1.1)
Traceback (most recent call last):
...
TypeError: Input value must be a 'int' type
>>> count_one_bits("0")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if number < 0:
raise ValueError("the value of input must be positive")
elif isinstance(number, float):
raise TypeError("Input value must be a 'int' type")
elif isinstance(number, str):
raise TypeError("'<' not supported between instances of 'str' and 'int'")
result = 0
while number:
if number % 2 == 1:
result += 1
number = number >> 1
return result


if __name__ == "__main__":
import doctest

doctest.testmod()