forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnaringst.js
61 lines (53 loc) Β· 1.79 KB
/
naringst.js
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* @param {number} n
* @return {number[]}
*/
/**
* Runtime: 82ms, Memory: 57.03MB
*
* Time complexity: O(logN < N+1 ? N+1 : logN λ¨,보ν΅μ κ²½μ° N+1)
* Space complexity: O(N+1)
*
* Note: necessary to think of an alternative approach
* **/
function decimalToBinary(decimal) {
let binaryBitCount = 0;
while (decimal > 1) {
binaryBitCount += decimal % 2 === 1 ? 1 : 0;
decimal = Math.floor(decimal / 2);
}
binaryBitCount += decimal === 1 ? 1 : 0;
return binaryBitCount;
}
var countBits = function (n) {
const answer = [];
for (let i = 0; i < n + 1; i++) {
answer.push(decimalToBinary(i));
}
return answer;
};
/**
* μΈμ κΉμλ νμ΄
*
* Runtime : 60ms
*
* λΉνΈ μ°μ°μ μμ±κ³Ό dpλ₯Ό νμ©ν΄ νΌ νμ΄
*
* [κ°λ¨μ€λͺ
]
* 4μΌλ 100μ΄κ³ , 5μΌλ 101, 6μΌλ 110μ΄λ€.
* μ΄λ 4λ₯Ό 2μ§μλ‘ ννν 100μ΄ κ°μ§ 1μ κ°μλ₯Ό νμ©ν΄ 5,6μ 1μ κ°μλ₯Ό μ°Ύλ κ²μ΄λ€.
* 100μμ 1μ λν 101μ΄λ, 110μ 100μ 1μ κ°μμΈ 1κ°μμ 1μ λν 2κ°κ° λλ€.
* result[5 & 4] => λΉνΈ μ°μ°μ ν΅ν΄ 100κ³Ό 101μ λΉνΈ μ€λ μ°μ°μ ν΄μ 100μ΄ λκ³ , μ΄λ 101μ κ°μ₯ μ€λ₯Έμͺ½ 1μ μ κ±°ν κ°μ΄ λλ€.
* result[6 & 5] => λΉνΈ μ°μ°μ ν΅ν΄ 110κ³Ό 101μ λΉνΈ μ€λ μ°μ°μ ν΄μ 100μ΄ λκ³ , μ΄λ 110μ κ°μ₯ μ€λ₯Έμͺ½ 1μ μ κ±°ν κ°μ΄ λλ€.
* μ΄μ§μλ 1μ© λνκΈ° λλ¬Έμ λλ³΄λ€ νλ ν° μμ μ€λ μ°μ°μ νλ©΄ μμ μκ° 0μΌλ‘ λλλ©΄ ν° μλ 1λ‘ λλκ³ ,
* μμ μκ° 1λ‘ λλλ©΄ ν° μλ 0μΌλ‘ λλκΈ° λλ¬Έμ μ΄λ° μμ±μ κ°λλ€.
*
*
*/
var countBits = function (n) {
let result = new Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
result[i] = result[i & (i - 1)] + 1;
}
return result;
};