[백준 18403] KABISA (C#, C++) - soo:bak
작성일 :
문제 링크
설명
주어진 연도 목록에서 윤년에 해당하는 연도만 골라 출력하는 문제입니다.
접근법
문제에서는 4년마다 하루를 추가한다고 설명하므로, 연도가 4로 나누어떨어지면 윤년으로 판단하면 됩니다.
연도 목록은 쉼표로 구분되어 있고 쉼표 뒤에 공백이 올 수 있습니다. 입력 줄에서 쉼표를 공백으로 바꾼 뒤 숫자를 하나씩 읽으면 쉽게 처리할 수 있습니다.
읽은 연도 중 year % 4 == 0인 값만 순서대로 모아 공백으로 구분해 출력하면 됩니다.
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
using System;
using System.Collections.Generic;
class Program {
static void Main() {
int t = int.Parse(Console.ReadLine()!);
for (int tc = 0; tc < t; tc++) {
string line = Console.ReadLine()!.Replace(',', ' ');
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var leapYears = new List<string>();
for (int i = 0; i < parts.Length; i++) {
int year = int.Parse(parts[i]);
if (year % 4 == 0)
leapYears.Add(year.ToString());
}
Console.WriteLine(string.Join(" ", leapYears));
}
}
}
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
30
31
32
33
34
35
36
37
38
39
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
cin.ignore();
while (t--) {
string line;
getline(cin, line);
for (char& ch : line) {
if (ch == ',')
ch = ' ';
}
stringstream ss(line);
vector<int> leapYears;
int year;
while (ss >> year) {
if (year % 4 == 0)
leapYears.push_back(year);
}
for (int i = 0; i < (int)leapYears.size(); i++) {
if (i > 0)
cout << ' ';
cout << leapYears[i];
}
cout << "\n";
}
return 0;
}