작성일 :

문제 링크

2139번 - 나는 너가 살아온 날을 알고 있다

설명

주어진 날짜가 해당 연도의 1월 1일부터 몇 번째 날인지 출력하는 문제입니다.


접근법

먼저 윤년 여부를 판단하여 2월의 일수를 조정합니다.

이후 월별 일수를 배열로 두고, 1월부터 이전 달까지의 합에 해당 일을 더해 몇 번째 날인지 계산합니다.


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
27
28
using System;

class Program {
  static bool IsLeap(int y) {
    if (y % 400 == 0) return true;
    if (y % 100 == 0) return false;
    return y % 4 == 0;
  }

  static void Main() {
    while (true) {
      var parts = Console.ReadLine()!.Split();
      var d = int.Parse(parts[0]);
      var m = int.Parse(parts[1]);
      var y = int.Parse(parts[2]);
      if (d == 0 && m == 0 && y == 0) break;

      var days = new[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
      if (IsLeap(y)) days[1] = 29;

      var total = d;
      for (var i = 0; i < m - 1; i++)
        total += days[i];

      Console.WriteLine(total);
    }
  }
}

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
27
28
29
#include <bits/stdc++.h>
using namespace std;

bool isLeap(int y) {
  if (y % 400 == 0) return true;
  if (y % 100 == 0) return false;
  return y % 4 == 0;
}

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

  while (true) {
    int d, m, y; cin >> d >> m >> y;
    if (d == 0 && m == 0 && y == 0) break;

    int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
    if (isLeap(y)) days[1] = 29;

    int total = d;
    for (int i = 0; i < m - 1; i++)
      total += days[i];

    cout << total << "\n";
  }

  return 0;
}