题解 | #日期差值#

日期差值

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

#include<cstdio>
int main() {
    int Mday[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int year1, mon1, day1;
    int year2, mon2, day2;
    bool isBefore ;
    scanf("%04d%02d%02d", &year1, &mon1, &day1);
    scanf("%04d%02d%02d", &year2, &mon2, &day2);
    if (year1 < year2
            || year1 == year2 && mon1 < mon2
            || year1 == year2 && mon1 == mon2 && day1 < day2
       ) {
        isBefore = true;
    } else {
        isBefore = false;
    }
    bool isLeap1 ;
    if (year1 % 400 == 0 || year1 % 100 != 0 && year1 % 4 == 0) {
        isLeap1 = true;
    } else {
        isLeap1 = false;
    }
    bool isLeap2 ;
    if (year2 % 400 == 0 || year2 % 100 != 0 && year2 % 4 == 0) {
        isLeap2 = true;
    } else {
        isLeap2 = false;
    }

    int totalday = 0;
    if (isBefore) {
        while (true) {
            if (year1 == year2 && mon1 == mon2 && day1 == day2) {
                break;
            } else {
                if (isLeap1 || isLeap2) {
                    Mday[2] = 29;
                } else {
                    Mday[2] = 28;
                }
                ++day1;
                ++totalday;
                if (day1 > Mday[mon1]) {
                    ++mon1;
                    day1 = 1;
                    if (mon1 > 12) {
                        ++year1;
                        mon1 = 1;
                    }
                }
            }

        }
    } else {
        while (true) {
            if (year1 == year2 && mon1 == mon2 && day1 == day2) {
                break;
            } else {
                if (isLeap1 || isLeap2) {
                    Mday[2] = 29;
                } else {
                    Mday[2] = 28;
                }
                ++day2;
                ++totalday;
                if (day2 > Mday[mon2]) {
                    ++mon2;
                    day2 = 1;
                    if (mon2 > 12) {
                        ++year2;
                        mon2 = 1;
                    }
                }
            }

        }
    }
    printf("%d\n", totalday + 1);
}

全部评论

相关推荐

昨天 11:40
海南大学 Java
点赞 评论 收藏
分享
双非硬上算法:洗洗睡吧,说多了都是遗憾,说白了都是扯淡
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务