We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 2a9a6f8 commit 0911277Copy full SHA for 0911277
1 file changed
number-of-1-bits/jylee2033.py
@@ -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