File tree 2 files changed +85
-0
lines changed
2 files changed +85
-0
lines changed Original file line number Diff line number Diff line change
1
+ def 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
+
38
+ if __name__ == "__main__" :
39
+ import doctest
40
+
41
+ doctest .testmod ()
Original file line number Diff line number Diff line change
1
+ from math import log2
2
+
3
+
4
+ def binary_count_trailing_zeros (a : int ) -> int :
5
+ """
6
+ Take in 1 integer, return a number that is
7
+ the number of trailing zeros in binary representation of that number.
8
+
9
+ >>> binary_count_trailing_zeros(25)
10
+ 0
11
+ >>> binary_count_trailing_zeros(36)
12
+ 2
13
+ >>> binary_count_trailing_zeros(16)
14
+ 4
15
+ >>> binary_count_trailing_zeros(58)
16
+ 1
17
+ >>> binary_count_trailing_zeros(4294967296)
18
+ 32
19
+ >>> binary_count_trailing_zeros(0)
20
+ 0
21
+ >>> binary_count_trailing_zeros(-10)
22
+ Traceback (most recent call last):
23
+ ...
24
+ ValueError: Input value must be a positive integer
25
+ >>> binary_count_trailing_zeros(0.8)
26
+ Traceback (most recent call last):
27
+ ...
28
+ TypeError: Input value must be a 'int' type
29
+ >>> binary_count_trailing_zeros("0")
30
+ Traceback (most recent call last):
31
+ ...
32
+ TypeError: '<' not supported between instances of 'str' and 'int'
33
+ """
34
+ if a < 0 :
35
+ raise ValueError ("Input value must be a positive integer" )
36
+ elif isinstance (a , float ):
37
+ raise TypeError ("Input value must be a 'int' type" )
38
+ return 0 if (a == 0 ) else int (log2 (a & - a ))
39
+
40
+
41
+ if __name__ == "__main__" :
42
+ import doctest
43
+
44
+ doctest .testmod ()
You can’t perform that action at this time.
0 commit comments