Skip to content

Commit 501faa7

Browse files
authored
Merge pull request #1 from code-a-key/count_set_bits
count_set_bits
2 parents 2c05963 + 2e25af5 commit 501faa7

File tree

2 files changed

+35
-11
lines changed

2 files changed

+35
-11
lines changed

Diff for: Bit Manipulation/3.3.1.count_set_bit_simple_method.py

+18-5
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,26 @@
66
IP: n = 9 [1001]
77
OP: 2
88
9-
TC:
10-
SC:
9+
TC: O(log n)
10+
SC: O(1)
1111
"""
1212
def 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

1629
if __name__ == '__main__':
17-
N = 9
18-
count_set_bits(N)
30+
N = 36
31+
print(count_set_bits(N))
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,29 @@
11
"""
2-
COUNT SET BITS - Method 1: Naive Method
2+
COUNT SET BITS - Method 2: Brain Karnighan's Algorithm
33
44
Count Number of 1's (set bits) in the binary representation of a given integer.
55
66
IP: n = 9 [1001]
77
OP: 2
88
9-
TC:
10-
SC:
9+
TC: O(logn)
10+
SC: O(1)
1111
"""
1212
def 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

1627
if __name__ == '__main__':
17-
N = 9
18-
count_set_bits(N)
28+
N = 36
29+
print(count_set_bits(N))

0 commit comments

Comments
 (0)