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)