본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1360. Number of Days Between Two Dates

반응형

https://leetcode.com/problems/number-of-days-between-two-dates/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

날짜 계산 문제였습니다.

📕 풀이방법

📔 풀이과정

1. -를 구분자로 연/월/일을 split하는 함수를 구현해 date1, date2에 각각 해당 함수 수행 후 yearMonthDay1, yearMonthDay2에 결과를 각각 저장해줍니다.2. C++20에서 지원하는 chrono의 year, month, day와 C++17부터 지원하는 year_month_day함수, 구조체를 이용해 chrono 내장 함수를 사용하기 편한 형태로 가공해 ymd1, ymd2에 각각 저장해줍니다.3. sys_datys함수를 이용해 1970-01-01부터의 일 수를 ymd1, ymd2 각각 계산한 후 count함수 이용해 차이에 대한 duration을 계산해 반환합니다.


📕 Code

📔 C++

#include <bits/stdc++.h>
class Solution {
public:
    vector <int> split(string input, char delimeter){
        vector <int> splited;
        stringstream ss(input);
        string tmp;
        while(getline(ss, tmp, delimeter)) {
            splited.push_back(stoi(tmp));
        }
        return splited;
    }
    int daysBetweenDates(string date1, string date2) {
        vector <string> dates = {date1, date2};
        sort(dates.begin(), dates.end());

        vector <int> yearMonthDay1 = split(dates[0], '-');
        vector <int> yearMonthDay2 = split(dates[1], '-');

        chrono::year_month_day ymd1{chrono::year(yearMonthDay1[0]),
                                    chrono::month(yearMonthDay1[1]),
                                    chrono::day(yearMonthDay1[2])};
        chrono::year_month_day ymd2{chrono::year(yearMonthDay2[0]),
                                    chrono::month(yearMonthDay2[1]),
                                    chrono::day(yearMonthDay2[2])};

        auto tp1 = chrono::sys_days{ymd1};
        auto tp2 = chrono::sys_days{ymd2};

        return (tp2 - tp1).count();
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.