File tree 2 files changed +35
-11
lines changed
2 files changed +35
-11
lines changed Original file line number Diff line number Diff line change 6
6
IP: n = 9 [1001]
7
7
OP: 2
8
8
9
- TC:
10
- SC:
9
+ TC: O(log n)
10
+ SC: O(1)
11
11
"""
12
12
def count_set_bits (num : int ) -> int :
13
- """Count set bits"""
13
+ """count set bits
14
14
15
+ Args:
16
+ num (int): input number
17
+
18
+ Returns:
19
+ int: number of set bits
20
+ """
21
+ count = 0
22
+ while num :
23
+ count += num & 1
24
+ num >>= 1
25
+ return count
26
+
27
+ # return bin(num).count('1')
15
28
16
29
if __name__ == '__main__' :
17
- N = 9
18
- count_set_bits (N )
30
+ N = 36
31
+ print ( count_set_bits (N ) )
Original file line number Diff line number Diff line change 1
1
"""
2
- COUNT SET BITS - Method 1: Naive Method
2
+ COUNT SET BITS - Method 2: Brain Karnighan's Algorithm
3
3
4
4
Count Number of 1's (set bits) in the binary representation of a given integer.
5
5
6
6
IP: n = 9 [1001]
7
7
OP: 2
8
8
9
- TC:
10
- SC:
9
+ TC: O(logn)
10
+ SC: O(1)
11
11
"""
12
12
def count_set_bits (num : int ) -> int :
13
- """Count set bits"""
13
+ """count set bits
14
14
15
+ Args:
16
+ num (int): input number
17
+
18
+ Returns:
19
+ int: number of set bits
20
+ """
21
+ count = 0
22
+ while num :
23
+ num = num & (num - 1 )
24
+ count += 1
25
+ return count
15
26
16
27
if __name__ == '__main__' :
17
- N = 9
18
- count_set_bits (N )
28
+ N = 36
29
+ print ( count_set_bits (N ) )
You can’t perform that action at this time.
0 commit comments