forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuraflower.js
More file actions
45 lines (37 loc) ยท 934 Bytes
/
uraflower.js
File metadata and controls
45 lines (37 loc) ยท 934 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* ๋ ๋ฒ์งธ ํ์ด
* ์๊ฐ๋ณต์ก๋: O(n)
* ๊ณต๊ฐ๋ณต์ก๋: O(n)
* @param {number} n
* @return {number[]}
*/
const countBits = function (n) {
const arr = [0];
for (let i = 1; i < n + 1; i++) {
arr[i] = arr[i >> 1] + (i & 1);
// i >> 1: ์ตํ์ ๋นํธ๋ฅผ ์ ์ธํ ๊ฐ. ์ด๊ฑธ ์ด์ฉํด์ ์ด์ ์ธ๋ฑ์ค ์ฌ์ฉ(dp)
// i // 2 (2๋ก ๋๋ ๋ชซ)์ ๊ฐ์.
// i & 1: ์ตํ์ ๋นํธ (1 ๋๋ 0)
}
return arr;
};
/**
* ์ฒซ ๋ฒ์งธ ํ์ด
* ์๊ฐ๋ณต์ก๋: O(n * log n)
* ๊ณต๊ฐ๋ณต์ก๋: O(n)
* @param {number} n
* @return {number[]}
*/
const countBits = function (n) {
const arr = [];
for (let i = 0; i < n + 1; i++) {
const bin = i.toString(2); // O(log n)
let num = 0;
// O(log n)
for (let char of bin) {
if (char === '1') num++;
}
arr.push(num);
}
return arr;
};