题解 | #日期差值#

日期差值

https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c

//王道讲的nextDay做法,很通用。KY_108也能做
#include "stdio.h"
#include "string"
using namespace std;
int monthDay[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
bool leapJudge(int year){
    if(year%4 == 0 && year%100 != 0 || year%400 == 0)
        return true;//true为闰年
    else
        return false;
}

int main(){
    char buf1[10],buf2[10];
    while (scanf("%s%s",buf1,buf2) != EOF){
        string date1 = buf1,date2 = buf2;
        string date_small = date1<date2?date1:date2;
        string date_big = date1>date2?date1:date2;
        int day1 = stoi(date_small.substr(6));
        int month1 = stoi(date_small.substr(4,2));
        int year1 = stoi(date_small.substr(0,4));
        int day2 = stoi(date_big.substr(6));
        int month2 = stoi(date_big.substr(4,2));
        int year2 = stoi(date_big.substr(0,4));
        int nextDay = 1;
        while (true){
            if (day1 == day2 && month1 == month2 && year1 == year2)
                break;
            nextDay++;
            day1++;
            bool flag = leapJudge(year1);
            if (day1 > monthDay[month1] && month1 != 2){
                day1 = 1;
                ++month1;
            } else if (day1 > monthDay[month1] && month1 == 2 && flag == false){
                day1 = 1;
                ++month1;
            } else if (day1 > monthDay[month1] && month1 == 2 && flag == true){
                if (day1 == 30){
                    day1 = 1;
                    ++month1;
                }
            }
            if(month1 > 12){
                month1 = 1;
                ++year1;
            }
        }
        printf("%d\n",nextDay);
    }
}

全部评论

相关推荐

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