문제 링크: https://www.hackerrank.com/challenges/utopian-tree/problem?isFullScreen=true
Utopian Tree | HackerRank
Predict the height of the tree after N growth cycles.
www.hackerrank.com
타입: Problem Solving (Basic)
🌳 문제 개요: Utopian Tree
유토피아 나무는 봄과 여름, 1년에 두 번 성장하는 특이한 나무야.
봄에는 키가 2배로 자라고,
여름에는 키가 1미터만큼 자라.
처음 나무의 키는 1미터부터 시작해.
주어진 성장 사이클 수(n) 만큼 나무가 자랐을 때, 최종 키를 구하는 문제야.
📘 성장 규칙
- 초기 키: 1
- 짝수 번째 사이클 (0, 2, 4, ...) → 봄 → 키 × 2
- 홀수 번째 사이클 (1, 3, 5, ...) → 여름 → 키 + 1
🧠 핵심 아이디어
- height = 1부터 시작
- 사이클을 0 ~ n-1까지 순회하면서
- 짝수면 곱하기 2 (봄)
- 홀수면 +1 (여름)
// 재귀 버전
public static int utopianTree(int n) {
return height(1, 0, n);
}
public static int height(int h, int c, int t) {
if(c == t) {
return h;
}
return height((c % 2 == 1 ? h + 1 : h * 2), c + 1, t);
}
// 반복문 버전
public static int utopianTree(int n) {
int height = 1;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
height *= 2; // 봄
} else {
height += 1; // 여름
}
}
return height;
}
'스터디 > HackerRank 문제 풀이' 카테고리의 다른 글
[숫자 뒤집기] Beautiful Days at the Movies (0) | 2025.04.13 |
---|---|
[이진탐색 구현] Climbing the Leaderboard (0) | 2025.04.13 |