Machineboy空
Excercism - Beer Song : 문자열 개행 본문
문제요약
Beer Song을 출력하라!
https://www.youtube.com/watch?v=6AfrLXrfOGQ
https://exercism.org/tracks/csharp/exercises/beer-song
Beer Song in C# on Exercism
Can you solve Beer Song in C#? Improve your C# skills with support from our world-class team of mentors.
exercism.org
난이도
Easy
풀이 포인트
- 개행
- 예외 케이스 처리: 1병 일 때 단수 표현, bottle과 it
startBottles == 1 ? "bottle" : "bottles"
REVIEW
간단한 반복문 문제라 생각해서 단순히 풀다가,
자꾸 몇 케이스가 틀려서 살펴보니 개행하는 타이밍과,
1병일 때 bottles가 아닌 bottle, take one이 아닌 take it으로 바꿔줘야 한다는 것을 간과했다..
반복문에서 마지막 케이스만 반복로직 중 하나를 빼야 할때 (여기서는 개행) 등의 잘 쓰이는 로직을 연습할 수 있는 문제라 정리해둔다!
CODE
using System;
public static class BeerSong
{
public static string Recite(int startBottles, int takeDown)
{
string answer = "";
while (takeDown > 0)
{
if (startBottles > 0)
{
// 병이 하나 이상 남았을 때
answer += $"{startBottles} {(startBottles == 1 ? "bottle" : "bottles")} of beer on the wall, {startBottles} {(startBottles == 1 ? "bottle" : "bottles")} of beer.\n";
startBottles--;
answer += $"Take {(startBottles == 0 ? "it" : "one")} down and pass it around, {(startBottles > 0 ? $"{startBottles} {(startBottles == 1 ? "bottle" : "bottles")}" : "no more bottles")} of beer on the wall.\n";
}
else
{
// 병이 없을 때
answer += "No more bottles of beer on the wall, no more bottles of beer.\n";
answer += "Go to the store and buy some more, 99 bottles of beer on the wall.\n";
}
takeDown--;
// 추가 줄바꿈 삽입 (takeDown이 남아있을 때만)
if (takeDown > 0)
{
answer += "\n";
}
}
return answer.Trim(); // 마지막 불필요한 공백 제거
}
}
'Computer > Coding Test' 카테고리의 다른 글
Excercism - Robot Name : Random, 중복체크, 아스키코드 (0) | 2025.02.04 |
---|---|
Excercism - Anagram (0) | 2025.01.24 |
Excercism - Rail Fence Cipher : 지그재그, 1,-1 방향 조절 (0) | 2025.01.23 |
Excercism - CryptoSquare : 문자열 ✅ (0) | 2025.01.22 |
Excercism - Binary Search : 이진탐색, 이진탐색 트리 (0) | 2025.01.22 |