题解 | #计算日期到天数转换#

#include <bits/stdc++.h>

using namespace std;

//平年每一个月的天数
int pingYears[]={31,28,31,30,31,30,31,31,30,31,30,31};
//闰年每一个月的天数
int runYears[]={31,29,31,30,31,30,31,31,30,31,30,31};

bool checkRunYear(int year){
    //用来判断年是不是闰年
    if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)){
        return true;
    }
    
    return false;
}

int main(){
    /*输入方式一
    int a, b, c;
    cin >> a >> b >> c;*/
    
    string str = "";
    while(getline(cin, str)){
        int res = 0;
        //cout << str << endl;
        /*输入方式二
        stringstream iss(str);
        string tmp = "";
        while(getline(iss, tmp, ' ')){
            //cout << tmp << endl;        
        }*/
        
        //输入方式三
        regex patten("^([^ ]*) ([^ ]*) ([^ ]*)$");
		smatch subMatch;
		if (regex_match(str, subMatch, patten)){ //
            int year = stoi(subMatch[1]);
            int month = stoi(subMatch[2]);
            int day = stoi(subMatch[3]);          
            //cout << year << month << day << endl;
            
            //判断是平年还是闰年
            if(checkRunYear(year)){
                //是闰年
                for(int i = 0; i < month - 1; i++){
                    res += runYears[i]; //先计算前 month - 1 个月的天数
                }
                res += day; //加上本月已过的天数
            }
            else{
                //是平年
                for(int i = 0; i < month - 1; i++){
                    res += pingYears[i]; //先计算前 month - 1 个月的天数
                }
                res += day; //加上本月已过的天数
            }
            
        }
        
        cout << res << endl;
    }
    
    return 0;
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务