C++:: 프로그래머스 <개인정보 수집 유효기간>

jahlee·2023년 3월 1일
0

프로그래머스_Lv.1

목록 보기
4/75
post-thumbnail

내장 함수를 사용하지않아서 직접 구현을 한 부분 들이 있다. 이미 구현된 함수를 알고 사용했다면 시간을 훨씬 단축할 수 있었을것 같다.

#include <string>
#include <vector>

using namespace std;

int ymd_to_int(string ymd)// ==> stoi를 사용하면된다. 
{
    int ans = 0;
    for(int i=0;i<ymd.size();i++)
        if (isdigit(ymd[i])) ans = ans*10 + ymd[i] - '0';
    return ans;
}

int expire_date(int n, char c, vector<string> terms)
{
    int tmp;
    int n_year, n_month, n_day;
    n_year = n/10000;
    n_month = (n%10000) / 100;
    n_day = n%100;
    for(int i=0;i<terms.size();i++)
    {
        if(terms[i][0] == c)
        {
            tmp = ymd_to_int(terms[i]); // 약관에 따른 개월수 
            break;
        }
    }
    if ((n_month+tmp)%12 == 0) // 12로 나누어 떨어지면 
    {
        n_year += (n_month+tmp)/12 - 1;
        n_month = 12;
    }
    else
    {
        n_year += (n_month+tmp)/12;
        n_month = (n_month+tmp)%12;
    }
    return (n_year*10000 + n_month*100 + n_day);
}

vector<int> solution(string today, vector<string> terms, vector<string> privacies)
{
    /*
        terms[i][0] 약관종류, terms[i][2] ~ terms[i][4]약관
        privacies[i][0]~[i][3] 년, privacies[i][5]~[i][6] 월, privacies[i][8]~[i][9] 일
        privacies[i][11] 약관종류
    */
    vector<int> answer;
    int today_int = ymd_to_int(today); // 현재 날짜 정수로 변환. 2023.03.01 => 20230301
    for(int i=0;i<privacies.size();i++)
    {
        int tmp = expire_date(ymd_to_int(privacies[i]), privacies[i][11], terms);
        if(tmp <= today_int) answer.push_back(i+1); // 만약 현재 날짜가 만기일자와 같거나 크면
    }
    return answer;
}

string.substr && stoi 사용법

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{

    string date = "2023.03.01";
    string year = date.substr(0,4); // substr(잘라낼 시작 인덱스, 길이)
    string month = date.substr(5,2);
    string day = date.substr(8,2);
    cout << "year : " << year << '\n';
    cout << "month : " << month << '\n';
    cout << "day : " << day << '\n';
    int tmp = stoi(date);//숫자부분까지만 아토이 해준다.
    cout << "stoi : " << tmp << "\n";
    return 0;
}

0개의 댓글