Skip to content

Commit

Permalink
2: counting bits
Browse files Browse the repository at this point in the history
  • Loading branch information
whewchews committed Aug 23, 2024
1 parent 33af494 commit 31b7ee6
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions counting-bits/whewchews.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
function countBits(n: number): number[] {
// SC: O(N)
const ans = Array(n + 1).fill(0);
// TC: O(N)
for (let i = 1; i <= n; i++) {
let k = i;

// TC: O(log N)
while (k > 0) {
ans[i] += k % 2;
k = Math.floor(k / 2);
}
}

return ans;
}

// TC: O(N log N)
// SC: O(N)

0 comments on commit 31b7ee6

Please sign in to comment.