본문 바로가기

숨막히는 알고말고/문제 풀이

[SWEA] 연월일 달력(Difficulty 2)

👀 문제 설명

문제

로그인해야 문제를 볼 수 있다

✍🏻풀이

간단한 문제였다. string으로 입력받고, 4자리 / 2자리 / 2자리 숫자를 잘라, year, month, day에 넣는다.

month와 day가 적합한 날짜인지 판단하고, 아니라면 -1을 출력하면 된다.

 

코드

#include <stdio.h>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    
    int T;
    cin >> T;
    
    vector<string> dates;
    for (int i = 0; i < T; i++) {
        string date;
        cin >> date;
        dates.push_back(date);
    }
    
    for (int i = 0; i < dates.size(); i++) {
        cout << "#" << i + 1 << " ";
        string cur = dates.at(i);
        
        string year = (cur.substr(0, 4));
        string month = (cur.substr(4, 2));
        string day = (cur.substr(6, 2));
        
        if (stoi(month) <= 0 || stoi(month) >= 12 || stoi(day) <= 0 || stoi(day) >= 32) {
            cout << -1 << endl;
            continue;
        }
        
        if (stoi(month) == 2) {
            if (stoi(day) >= 29) {
                cout << -1 << endl;
                continue;
            }
        }
        
        if (stoi(month) == 4 || stoi(month) == 6 || stoi(month) == 9 || stoi(month) == 11) {
            if (stoi(day) >= 31) {
                cout << -1 << endl;
                continue;
            }
        }
        
        cout << year << "/" << month << "/" << day << endl;
    }
    
    return 0;
}