File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11class 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)
You can’t perform that action at this time.
0 commit comments