Skip to content

Commit 62e5691

Browse files
committed
Counting Bits Solutions
1 parent c04e4f6 commit 62e5691

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

β€Žcounting-bits/naringst.jsβ€Ž

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* @param {number} n
3+
* @return {number[]}
4+
*/
5+
6+
/**
7+
* Runtime: 82ms, Memory: 57.03MB
8+
*
9+
* Time complexity: O(logN < N+1 ? N+1 : logN 단,λ³΄ν†΅μ˜ 경우 N+1)
10+
* Space complexity: O(N+1)
11+
*
12+
* Note: necessary to think of an alternative approach
13+
* **/
14+
15+
function decimalToBinary(decimal) {
16+
let binaryBitCount = 0;
17+
18+
while (decimal > 1) {
19+
binaryBitCount += decimal % 2 === 1 ? 1 : 0;
20+
decimal = Math.floor(decimal / 2);
21+
}
22+
binaryBitCount += decimal === 1 ? 1 : 0;
23+
24+
return binaryBitCount;
25+
}
26+
var countBits = function (n) {
27+
const answer = [];
28+
29+
for (let i = 0; i < n + 1; i++) {
30+
answer.push(decimalToBinary(i));
31+
}
32+
33+
return answer;
34+
};
35+
36+
/**
37+
* 인상 κΉŠμ—ˆλ˜ 풀이
38+
*
39+
* Runtime : 60ms
40+
*
41+
* λΉ„νŠΈ μ—°μ‚°μ˜ 속성과 dpλ₯Ό ν™œμš©ν•΄ ν‘Ό 풀이
42+
*
43+
* [간단섀λͺ…]
44+
* 4μΌλ•Œ 100이고, 5μΌλ•Œ 101, 6μΌλ•Œ 110이닀.
45+
* μ΄λ•Œ 4λ₯Ό 2μ§„μˆ˜λ‘œ ν‘œν˜„ν•œ 100이 κ°€μ§„ 1의 개수λ₯Ό ν™œμš©ν•΄ 5,6의 1의 개수λ₯Ό μ°ΎλŠ” 것이닀.
46+
* 100μ—μ„œ 1을 λ”ν•œ 101μ΄λ‚˜, 110은 100의 1의 개수인 1κ°œμ—μ„œ 1을 λ”ν•œ 2κ°œκ°€ λœλ‹€.
47+
* result[5 & 4] => λΉ„νŠΈ 연산을 톡해 100κ³Ό 101의 λΉ„νŠΈ μ•€λ“œ 연산을 ν•΄μ„œ 100이 되고, μ΄λŠ” 101의 κ°€μž₯ 였λ₯Έμͺ½ 1을 μ œκ±°ν•œ 값이 λœλ‹€.
48+
* result[6 & 5] => λΉ„νŠΈ 연산을 톡해 110κ³Ό 101의 λΉ„νŠΈ μ•€λ“œ 연산을 ν•΄μ„œ 100이 되고, μ΄λŠ” 110의 κ°€μž₯ 였λ₯Έμͺ½ 1을 μ œκ±°ν•œ 값이 λœλ‹€.
49+
* μ΄μ§„μˆ˜λŠ” 1μ”© λ”ν•˜κΈ° λ•Œλ¬Έμ— λ‚˜λ³΄λ‹€ ν•˜λ‚˜ 큰 μˆ˜μ™€ μ•€λ“œ 연산을 ν•˜λ©΄ μž‘μ€ μˆ˜κ°€ 0으둜 λλ‚˜λ©΄ 큰 μˆ˜λŠ” 1둜 λλ‚˜κ³ ,
50+
* μž‘μ€ μˆ˜κ°€ 1둜 λλ‚˜λ©΄ 큰 μˆ˜λŠ” 0으둜 λλ‚˜κΈ° λŒ€λ¬Έμ— 이런 속성을 κ°–λŠ”λ‹€.
51+
*
52+
*
53+
*/
54+
55+
var countBits = function (n) {
56+
let result = new Array(n + 1).fill(0);
57+
for (let i = 1; i <= n; i++) {
58+
result[i] = result[i & (i - 1)] + 1;
59+
}
60+
return result;
61+
};

0 commit comments

Comments
Β (0)