Skip to content

Commit 1721337

Browse files
authored
[ PS ] : Counting Bits
1 parent 499d198 commit 1721337

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

โ€Žcounting-bits/uraflower.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* ๋‘ ๋ฒˆ์งธ ํ’€์ด
3+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
4+
* ๊ณต๊ฐ„๋ณต์žก๋„: O(n)
5+
* @param {number} n
6+
* @return {number[]}
7+
*/
8+
const countBits = function (n) {
9+
const arr = [0];
10+
11+
for (let i = 1; i < n + 1; i++) {
12+
arr[i] = arr[i >> 1] + (i & 1);
13+
// i >> 1: ์ตœํ•˜์œ„ ๋น„ํŠธ๋ฅผ ์ œ์™ธํ•œ ๊ฐ’. ์ด๊ฑธ ์ด์šฉํ•ด์„œ ์ด์ „ ์ธ๋ฑ์Šค ์‚ฌ์šฉ(dp)
14+
// i // 2 (2๋กœ ๋‚˜๋ˆˆ ๋ชซ)์™€ ๊ฐ™์Œ.
15+
// i & 1: ์ตœํ•˜์œ„ ๋น„ํŠธ (1 ๋˜๋Š” 0)
16+
}
17+
18+
return arr;
19+
};
20+
21+
/**
22+
* ์ฒซ ๋ฒˆ์งธ ํ’€์ด
23+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(n * log n)
24+
* ๊ณต๊ฐ„๋ณต์žก๋„: O(n)
25+
* @param {number} n
26+
* @return {number[]}
27+
*/
28+
const countBits = function (n) {
29+
const arr = [];
30+
31+
for (let i = 0; i < n + 1; i++) {
32+
const bin = i.toString(2); // O(log n)
33+
34+
let num = 0;
35+
36+
// O(log n)
37+
for (let char of bin) {
38+
if (char === '1') num++;
39+
}
40+
41+
arr.push(num);
42+
}
43+
44+
return arr;
45+
};

0 commit comments

Comments
ย (0)