Skip to content

Commit 1c5fdaf

Browse files
committed
solve: counting bits
1 parent 7672c10 commit 1c5fdaf

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

counting-bits/evan.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {number} n
3+
* @return {number[]}
4+
*/
5+
var countBits = function (n) {
6+
const result = new Array(n + 1).fill(0);
7+
8+
for (let i = 1; i <= n; i++) {
9+
/** The number of 1's in i divided by 2, except last bit of i */
10+
const totalOnes = result[i >> 1];
11+
const lastBit = i & 1;
12+
13+
result[i] = totalOnes + lastBit;
14+
}
15+
16+
return result;
17+
};
18+
19+
/**
20+
* Time Complexity: O(n), where n is number input
21+
* Reason: The algorithm processes each number from 1 to n exactly once.
22+
*
23+
* Space Complexity: O(n), where n is number input
24+
* Reason: The algorithm uses an array of size n + 1
25+
*/

0 commit comments

Comments
 (0)