We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ae68a78 commit f22fe48Copy full SHA for f22fe48
bit_manipulation/count_bits.py
@@ -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
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