작성일 :

문제 링크

17293번 - 맥주 99병

설명

N병부터 시작해 규칙에 따라 가사를 출력하는 문제입니다.


접근법

K병부터 1병까지 반복하며 두 줄을 출력합니다.

병의 개수에 따라 bottle/bottles, no more bottles 표현을 구분합니다.

모두 소진되면 마지막 두 줄을 출력합니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Text;

class Program {
  static string Bottle(int n) {
    if (n == 0) return "no more bottles";
    if (n == 1) return "1 bottle";
    return $"{n} bottles";
  }

  static void Main() {
    var n = int.Parse(Console.ReadLine()!);
    var sb = new StringBuilder();

    for (var k = n; k >= 1; k--) {
      sb.AppendLine($"{Bottle(k)} of beer on the wall, {Bottle(k)} of beer.");
      sb.AppendLine($"Take one down and pass it around, {Bottle(k - 1)} of beer on the wall.");
      sb.AppendLine();
    }

    sb.AppendLine("No more bottles of beer on the wall, no more bottles of beer.");
    sb.AppendLine($"Go to the store and buy some more, {Bottle(n)} of beer on the wall.");

    Console.Write(sb.ToString());
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <bits/stdc++.h>
using namespace std;

string bottle(int n) {
  if (n == 0) return "no more bottles";
  if (n == 1) return "1 bottle";
  return to_string(n) + " bottles";
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n; cin >> n;
  for (int k = n; k >= 1; k--) {
    cout << bottle(k) << " of beer on the wall, " << bottle(k) << " of beer.\n";
    cout << "Take one down and pass it around, " << bottle(k - 1) << " of beer on the wall.\n\n";
  }

  cout << "No more bottles of beer on the wall, no more bottles of beer.\n";
  cout << "Go to the store and buy some more, " << bottle(n) << " of beer on the wall.\n";

  return 0;
}