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 all commits
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
34 changes: 34 additions & 0 deletions bit_manipulation/count_number_of_one_bits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
def get_set_bits_count(number: int) -> int:
"""
Count the number of set bits in a 32 bit integer
>>> get_set_bits_count(25)
3
>>> get_set_bits_count(37)
3
>>> get_set_bits_count(21)
3
>>> get_set_bits_count(58)
4
>>> get_set_bits_count(0)
0
>>> get_set_bits_count(256)
1
>>> get_set_bits_count(-1)
Traceback (most recent call last):
...
ValueError: the value of input must be positive
"""
if number < 0:
raise ValueError("the value of input must be positive")
result = 0
while number:
if number % 2 == 1:
result += 1
number = number >> 1
return result


if __name__ == "__main__":
import doctest

doctest.testmod()