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 4d68b2a commit 355a40cCopy full SHA for 355a40c
counting-bits/HC-kang.ts
@@ -0,0 +1,26 @@
1
+// T.C: O(n)
2
+// S.C: O(n)
3
+function countBits(n: number): number[] {
4
+ // T.C: O(1)
5
+ // S.C: O(1)
6
+ function countBit(num: number): number {
7
+ num = num - ((num >>> 1) & 0x55555555);
8
+ num = (num & 0x33333333) + ((num >>> 2) & 0x33333333);
9
+ num = (num + (num >>> 4)) & 0x0f0f0f0f;
10
+ num = num + (num >>> 8);
11
+ num = num + (num >>> 16);
12
+ return num & 0x3f;
13
+ }
14
+
15
+ return new Array(n + 1).fill(0).map((_, i) => countBit(i));
16
+}
17
18
19
20
21
+ const dp = new Array(n + 1).fill(0);
22
+ for (let i = 1; i <= n; i++) {
23
+ dp[i] = dp[i >> 1] + (i & 1);
24
25
+ return dp;
26
0 commit comments