Skip to content

Commit 44fe6c2

Browse files
count-bits
1 parent 03d3435 commit 44fe6c2

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
def count_one_bits(number: int) -> int:
2+
"""
3+
Take in an 32 bit integer, count the number of one bits,
4+
return the number of one bits
5+
result of a count_one_bits and operation on the integer provided.
6+
>>> count_one_bits(25)
7+
3
8+
>>> count_one_bits(37)
9+
3
10+
>>> count_one_bits(21)
11+
3
12+
>>> count_one_bits(58)
13+
4
14+
>>> count_one_bits(0)
15+
0
16+
>>> count_one_bits(256)
17+
1
18+
>>> count_one_bits(-1)
19+
Traceback (most recent call last):
20+
...
21+
ValueError: the value of input must be positive
22+
>>> count_one_bits(1.1)
23+
Traceback (most recent call last):
24+
...
25+
TypeError: Input value must be a 'int' type
26+
>>> count_one_bits("0")
27+
Traceback (most recent call last):
28+
...
29+
TypeError: '<' not supported between instances of 'str' and 'int'
30+
"""
31+
if number < 0:
32+
raise ValueError("the value of input must be positive")
33+
elif isinstance(number, float):
34+
raise TypeError("Input value must be a 'int' type")
35+
elif isinstance(number, str):
36+
raise TypeError("'<' not supported between instances of 'str' and 'int'")
37+
result = 0
38+
while number:
39+
if number % 2 == 1:
40+
result += 1
41+
number = number >> 1
42+
return result
43+
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
48+
doctest.testmod()

0 commit comments

Comments
 (0)