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.
2024-02-08 2885_초콜릿 식사
🔗 문제 링크
2885번: 초콜릿 식사
✔️ 소요된 시간
40분 + α
✨ 수도 코드
1. 문제 이해
조건
2. 코드 분석
square
에 만들어야 하는 정사각형의 크기를 입력받는다.상근이가 구매해야하는 가장 작은 초콜릿의 크기인
size
를 구하는 과정은 다음과 같다.1부터 시작해서 square보다 size가 커지기 전까지 2를 곱해주면 된다. 초콜릿의 크기는 2의 제곱(1, 2, 4, 8, ...)이면서 가장 작은 초콜릿의 크기를 구해야하므로 size를 넘지 않는 2의 제곱을 구하면 되는 것이다.
| square = size
i
= size의 수와 같게 설정 (마지막에 size를 출력해야 하므로 size변수는 변화시키면 안되어서 따로 i 설정)cnt
= 초콜릿을 자른 횟수만들어야하는 정사각형의 크기인 square가 size와 같다면 그대로 size와 0을 출력해주면 된다.
Ex)
square = 4
-> 상근이가 길이가 4인 막대 초콜릿을 구매하면 가장 작은 초콜릿의 크기를 사게 되는 것이다. 그리고 자를 필요 없이 끝이므로
4 0
을 출력하게 된다.| square ≠ size
만들어야하는 정사각형의 크기인 square와 size가 같지 않다면, 다음과 같이 계산해주면 된다.
square ≠ 0 을 만족하는 동안, 2가지 조건에 따라 계산한다. 이때, i는 시작할 때의 size와 같은 수이다.
3. 예제 확인
square = 6
size = 8 -> 2의 제곱이자 6보다 크다는 조건을 만족하는 최소의 값
square ≠ size
이므로 square가 0이 될 때까지 위의 계산의 진행한다. (i = size = 8, cnt = 0)square = 6
<i = 8
-> i //= 2 -> i = 4, cnt = 1square = 6
>i = 4
-> square -= 4 -> square = 2 -> i = 2, cnt = 2square = 2
==i = 2
-> square -= 2 -> square = 0 -> i = 1, cnt = 3출력 : (size = 8, cnt-1 = 2)
출력할 때,
cnt-1
을 출력해주는 이유는 계산에서의 마지막 계산(위의 3번 계산)을 보면 알 수 있다.마지막 계산은 초콜릿을 절반으로 쪼개지 않아도 된다. 어차피, square = 0이 되는 즉, 여분의 초콜릿을 더 쪼개내지 않아도 원하는 크기의 초콜릿을 얻을 수 있기 때문이다. 그래서 최종 cnt에서 1을 빼주는 것이다.
4. 전체 코드
📚 새롭게 알게된 내용
새롭게 알게 된 점은 없습니다!