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

counting-bits/YeomChaeeun.ts

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)