Skip to content

Commit 909b6d7

Browse files
committed
number of 1 bits solution refactor
1 parent 00093a4 commit 909b6d7

1 file changed

Lines changed: 26 additions & 13 deletions

File tree

number-of-1-bits/jylee2033.py

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,39 @@
11
class Solution:
22
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
3+
# # 1. Find highest power of 2 range that covers n
4+
# # 2. Greedily subtract from largest power of 2 to smallest
55

6-
# powers : 1 + 2 + 4 + 8 + 16 + ...
7-
# total : 1 + 3 + 7 + 15 + 31 + ...
8-
# index : 0 1 2 3 4
6+
# # powers : 1 + 2 + 4 + 8 + 16 + ...
7+
# # total : 1 + 3 + 7 + 15 + 31 + ...
8+
# # index : 0 1 2 3 4
99

10-
i = 0
11-
total = 1
10+
# i = 0
11+
# total = 1
1212

13-
while n > total:
14-
i += 1
15-
total += 2 ** i
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)
1628

1729
count = 0
1830

19-
for j in range(i, -1, -1):
20-
if n >= 2 ** j:
21-
n -= 2 ** j
31+
while n > 0:
32+
if n % 2 == 1:
2233
count += 1
2334

35+
n //= 2
36+
2437
return count
2538

2639
# Time Complexity : O(log n)

0 commit comments

Comments
 (0)