Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions counting-bits/socow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""
338. Counting Bits
https://leetcode.com/problems/counting-bits/
Solution:
DP를 활용한 풀이
- i의 1비트 개수 = (i // 2)의 1비트 개수 + (i % 2)
- i // 2는 i를 오른쪽으로 1비트 shift한 것 (이미 계산된 값)
- i % 2는 LSB(최하위 비트)가 1인지 여부
예시: 5 = 101(2)
- 5 // 2 = 2 = 10(2) → 1비트 1개
- 5 % 2 = 1 → LSB가 1
- 따라서 5의 1비트 개수 = 1 + 1 = 2
Time: O(n)
Space: O(1) - 결과 배열 제외
"""

from typing import List


class Solution:
def countBits(self, n: int) -> List[int]:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

비트연산과 DP를 활용한 풀이로 보입니다. 시간 복잡도를 O(n)으로 줄였다는 점이 인상적이었습니다.
저같은 경우에는 비트 연산이 익숙하지 않아 bin() 기반으로 카운팅하는 방식으로 풀었는데, 해당 풀이를 통해 비트 연산을 활용하면 더 효율적으로 해결할 수 있다는 점을 배울 수 있었습니다.
또한 주석 예시를 잘 작성해 주셔서 로직을 이해하는 데 도움이 되었습니다.

dp = [0] * (n + 1)

for i in range(1, n + 1):
dp[i] = dp[i >> 1] + (i & 1)

return dp