题解 | #日期差值#

日期差值

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

#include <stdio.h>
#include<stdbool.h>
//每月天数
int table[2][13] = {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
bool IsRunYear(int year) {
    return ((year % 4 == 0)&&(year%100!=0))||(year%400==0);
}
int NumberYear(int year) {
    if (IsRunYear(year) == 0)
        return 365;
    else
        return 366;
}
int main() {
    int year, month, day, newyear, newmonth, newday, number;
    while ((scanf("%04d%02d%02d\n%04d%02d%02d", &year, &month, &day, &newyear,
                  &newmonth,
                  &newday)) != EOF) {
        if (year == newyear && month == newmonth ) {
            number = newday - day + 1;
        }
        if (year == newyear && month != newmonth) {
            int row = IsRunYear(year);
            number = table[row][month] - day - 1;
            while (month + 1 != newmonth) {
                number += table[row][++month];
            }
            number += newday;
        } else {
            number = 0;
            int row = IsRunYear(year);
            for (int i = 0; i < month; i++) {
                number += table[row][i];
            }
            number += day;
            int sum = NumberYear(year) - number + 1;
            while (year + 1 != newyear) {
                sum += NumberYear(++year);
            }
            int newrow = IsRunYear(newyear);
            for (int j = 0; j < newmonth; j++) {
                sum += table[newrow][j];
            }
            sum += newday;
            number = sum;
        }
        printf("%d", number);
    }
    return 0;
}

全部评论

相关推荐

整顿职场的柯基很威猛:这种不可怕,最可怕的是夹在一帮名校里的二本选手,人家才是最稳的。
点赞 评论 收藏
分享
字节 飞书绩效团队 (n+2) * 15 + 1k * 12 + 1w
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务