File tree Expand file tree Collapse file tree 2 files changed +35
-11
lines changed
Expand file tree Collapse file tree 2 files changed +35
-11
lines changed Original file line number Diff line number Diff line change 66IP: n = 9 [1001]
77OP: 2
88
9- TC:
10- SC:
9+ TC: O(log n)
10+ SC: O(1)
1111"""
1212def count_set_bits (num : int ) -> int :
13- """Count set bits"""
13+ """count set bits
1414
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')
1528
1629if __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 11"""
2- COUNT SET BITS - Method 1: Naive Method
2+ COUNT SET BITS - Method 2: Brain Karnighan's Algorithm
33
44Count Number of 1's (set bits) in the binary representation of a given integer.
55
66IP: n = 9 [1001]
77OP: 2
88
9- TC:
10- SC:
9+ TC: O(logn)
10+ SC: O(1)
1111"""
1212def count_set_bits (num : int ) -> int :
13- """Count set bits"""
13+ """count set bits
1414
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
1526
1627if __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