Skip to content

Commit 0911277

Browse files
committed
number of 1 bits solution
1 parent 2a9a6f8 commit 0911277

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

number-of-1-bits/jylee2033.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def hammingWeight(self, n: int) -> int:
3+
# 1. Find highest power of 2 range that covers n
4+
# 2. Greedily subtract from largest power of 2 to smallest
5+
6+
# powers : 1 + 2 + 4 + 8 + 16 + ...
7+
# total : 1 + 3 + 7 + 15 + 31 + ...
8+
# index : 0 1 2 3 4
9+
10+
i = 0
11+
total = 1
12+
13+
while n > total:
14+
i += 1
15+
total += 2 ** i
16+
17+
count = 0
18+
19+
for j in range(i, -1, -1):
20+
if n >= 2 ** j:
21+
n -= 2 ** j
22+
count += 1
23+
24+
return count
25+
26+
# Time Complexity : O(log n)
27+
# Space Complexity : O(1)

0 commit comments

Comments
 (0)