Skip to content

Commit 97ff01e

Browse files
committed
1 parent 4bf2eed commit 97ff01e

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
def get_1s_count(number: int) -> int:
2+
"""
3+
Count the number of set bits in a 32 bit integer using Brian Kernighan's way.
4+
Ref - http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
5+
>>> get_1s_count(25)
6+
3
7+
>>> get_1s_count(37)
8+
3
9+
>>> get_1s_count(21)
10+
3
11+
>>> get_1s_count(58)
12+
4
13+
>>> get_1s_count(0)
14+
0
15+
>>> get_1s_count(256)
16+
1
17+
>>> get_1s_count(-1)
18+
Traceback (most recent call last):
19+
...
20+
ValueError: the value of input must be positive
21+
>>> get_1s_count(0.8)
22+
Traceback (most recent call last):
23+
...
24+
TypeError: Input value must be an 'int' type
25+
"""
26+
if number < 0:
27+
raise ValueError("the value of input must be positive")
28+
elif isinstance(number, float):
29+
raise TypeError("Input value must be an 'int' type")
30+
count = 0
31+
while number:
32+
# This way we arrive at next set bit (next 1) instead of looping
33+
# through each bit and checking for 1s hence the
34+
# loop won't run 32 times it will only run the number of `1` times
35+
number &= number - 1
36+
count += 1
37+
return count
38+
39+
40+
if __name__ == "__main__":
41+
import doctest
42+
43+
doctest.testmod()

0 commit comments

Comments
 (0)