题解 | 日期差值

日期差值

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

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

int month[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int month0[13] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

bool isrunnian(int year) {
    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
        return true;
    } else return false;
}

int main() {
    string a, b;
    int year1, year2, month1, month2, day1, day2;
    while (cin >> a >> b) {
        year1 = stoi(a.substr(0, 4));
        year2 = stoi(b.substr(0, 4));
        month1 = stoi(a.substr(4, 2));
        month2 = stoi(b.substr(4, 2));
        day1 = stoi(a.substr(6, 2));
        day2 = stoi(b.substr(6, 2));
        int ans1 = 0, ans2 = 0;
        for (int i = 0; i < year1; i++) {
            if (isrunnian(i)) {
                ans1 += 366;
            } else ans1 += 365;
        }
        for (int i = 0; i < year2; i++) {
            if (isrunnian(i)) {
                ans2 += 366;
            } else ans2 += 365;
        }
        for (int i = 0; i < month1; i++) {
            if (isrunnian(year1)) {
                ans1 += month0[i];
            } else ans1 += month[i];
        }
        for (int i = 0; i < month2; i++) {
            if (isrunnian(year2)) {
                ans2 += month0[i];
            } else ans2 += month[i];
        }
        ans1+=day1;
        ans2+=day2;
        cout<<(ans2-ans1+1)<<endl;
    }
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务