Skip to content

Commit f22fe48

Browse files
committed
feat: add count_bits algorithm with doctests
1 parent ae68a78 commit f22fe48

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

bit_manipulation/count_bits.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
def count_bits(n: int) -> int:
2+
"""
3+
Count the number of set bits (1s) in the binary representation of a
4+
non-negative integer.
5+
6+
Examples:
7+
>>> count_bits(0)
8+
0
9+
>>> count_bits(1)
10+
1
11+
>>> count_bits(5) # 101
12+
2
13+
>>> count_bits(15) # 1111
14+
4
15+
>>> count_bits(16) # 10000
16+
1
17+
"""
18+
if n < 0:
19+
raise ValueError("Input must be non-negative")
20+
21+
count = 0
22+
while n > 0:
23+
count += n & 1
24+
n >>= 1
25+
26+
return count
27+
28+
29+
if __name__ == "__main__":
30+
import doctest
31+
doctest.testmod()

0 commit comments

Comments
 (0)