Skip to content

Commit

Permalink
feat: 338. Counting Bits
Browse files Browse the repository at this point in the history
  • Loading branch information
HC-kang committed Aug 22, 2024
1 parent 4d68b2a commit 355a40c
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions counting-bits/HC-kang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// T.C: O(n)
// S.C: O(n)
function countBits(n: number): number[] {
// T.C: O(1)
// S.C: O(1)
function countBit(num: number): number {
num = num - ((num >>> 1) & 0x55555555);
num = (num & 0x33333333) + ((num >>> 2) & 0x33333333);
num = (num + (num >>> 4)) & 0x0f0f0f0f;
num = num + (num >>> 8);
num = num + (num >>> 16);
return num & 0x3f;
}

return new Array(n + 1).fill(0).map((_, i) => countBit(i));
}

// T.C: O(n)
// S.C: O(n)
function countBits(n: number): number[] {
const dp = new Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
dp[i] = dp[i >> 1] + (i & 1);
}
return dp;
}

0 comments on commit 355a40c

Please sign in to comment.