MCPcopy
hub / github.com/TheAlgorithms/Python / binary_count_setbits

Function binary_count_setbits

bit_manipulation/binary_count_setbits.py:1–35  ·  view source on GitHub ↗

Take in 1 integer, return a number that is the number of 1's in binary representation of that number. >>> binary_count_setbits(25) 3 >>> binary_count_setbits(36) 2 >>> binary_count_setbits(16) 1 >>> binary_count_setbits(58) 4 >>> binary_count_setbits(429

(a: int)

Source from the content-addressed store, hash-verified

1def binary_count_setbits(a: int) -> int:
2 """
3 Take in 1 integer, return a number that is
4 the number of 1's in binary representation of that number.
5
6 >>> binary_count_setbits(25)
7 3
8 >>> binary_count_setbits(36)
9 2
10 >>> binary_count_setbits(16)
11 1
12 >>> binary_count_setbits(58)
13 4
14 >>> binary_count_setbits(4294967295)
15 32
16 >>> binary_count_setbits(0)
17 0
18 >>> binary_count_setbits(-10)
19 Traceback (most recent call last):
20 ...
21 ValueError: Input value must be a positive integer
22 >>> binary_count_setbits(0.8)
23 Traceback (most recent call last):
24 ...
25 TypeError: Input value must be a 'int' type
26 >>> binary_count_setbits("0")
27 Traceback (most recent call last):
28 ...
29 TypeError: '<' not supported between instances of 'str' and 'int'
30 """
31 if a < 0:
32 raise ValueError("Input value must be a positive integer")
33 elif isinstance(a, float):
34 raise TypeError("Input value must be a 'int' type")
35 return bin(a).count("1")
36
37
38if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

countMethod · 0.80

Tested by

no test coverage detected