-
-
Notifications
You must be signed in to change notification settings - Fork 305
[sojae] WEEK 14 solutions #2327
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+30
−0
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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]: | ||
| dp = [0] * (n + 1) | ||
|
|
||
| for i in range(1, n + 1): | ||
| dp[i] = dp[i >> 1] + (i & 1) | ||
|
|
||
| return dp | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
비트연산과 DP를 활용한 풀이로 보입니다. 시간 복잡도를 O(n)으로 줄였다는 점이 인상적이었습니다.
저같은 경우에는 비트 연산이 익숙하지 않아 bin() 기반으로 카운팅하는 방식으로 풀었는데, 해당 풀이를 통해 비트 연산을 활용하면 더 효율적으로 해결할 수 있다는 점을 배울 수 있었습니다.
또한 주석 예시를 잘 작성해 주셔서 로직을 이해하는 데 도움이 되었습니다.