Skip to content

Commit da2339e

Browse files
Jeehay28Jeehay28
authored andcommitted
Add counting-bits solution in TS
1 parent 778edbb commit da2339e

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

counting-bits/Jeehay28.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// TC: O(n)
2+
// SC: O(n)
3+
function countBits(n: number): number[] {
4+
const dp: number[] = [];
5+
dp[0] = 0;
6+
7+
for (let i = 0; i <= n; i++) {
8+
dp[i] = dp[i >> 1] + (i & 1);
9+
}
10+
11+
// The number of 1s in the quotient (i >> 1) + number of 1s in the remainder (i & 1)
12+
// dp[i >> 1]: number of 1's in Math.floor(i / 2)
13+
// i & 1: 1 if i is odd, 0 if even
14+
15+
return dp;
16+
}
17+

0 commit comments

Comments
 (0)