Skip to content

Commit e9a055c

Browse files
committed
feat: counting-bits solution
1 parent e10ec05 commit e9a055c

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* ์ด์ง„์ˆ˜์—์„œ 1์˜ ๊ฐœ์ˆ˜ ์„ธ๊ธฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜
3+
* ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ณต์žก๋„
4+
* - ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n * log n)
5+
* - ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n)
6+
*/
7+
function countBits(n: number): number[] {
8+
const result: number[] = [];
9+
10+
// ๋น„ํŠธ ์—ฐ์‚ฐ์„ ์ด์šฉํ•ด 1์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๋Š” ํ•จ์ˆ˜ - O(log n)
11+
function countOnes(num: number): number {
12+
let count = 0;
13+
while (num > 0) {
14+
num &= (num - 1); // ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ์˜ 1 ๋น„ํŠธ๋ฅผ ์ œ๊ฑฐ
15+
count++;
16+
}
17+
return count;
18+
}
19+
20+
for (let i = 0; i <= n; i++) {
21+
result.push(countOnes(i));
22+
}
23+
24+
return result;
25+
}
26+

0 commit comments

Comments
ย (0)