题解 | #日期差值#

日期差值

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

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

int IsLeapYear(int year){
    return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0));
}

int main() {
    int year1,year2,month1,month2,day1,day2;
    int mon_day[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}};
    while (scanf("%4d%2d%2d",&year1,&month1,&day1)!=EOF) {
        scanf("%4d%2d%2d",&year2,&month2,&day2);
        
        int totalDay = 0;
        //思路是先判断两个年份的大小,大的年份就算日期相对于当年的1月1日的差值,小的年份算相对于当年的12月31日的差值
        //再根据两个年份中间相差几年进行,闰年就加366,平年就加365,例如:2013与2011中间只差2012年的366天,最后根据规定再多加一天。
	  //相同年份时,分别算距离当年12月31日相差多少天,最后相减取绝对值+1就是最终相差的天数
        if (year1>year2) {
            for (int i = month2 ; i <= 12 ; ++i ) {
                totalDay += mon_day[IsLeapYear(year2)][i] - day2;
                day2 = 0;
            }
            for (int j = 0; j < month1 ; ++j ) {
                totalDay += mon_day[IsLeapYear(year1)][j] + day1;
                day1 = 0;
            }
            for (int k = year2; k < year1-1; k++) {
                if (IsLeapYear(k)) {
                    totalDay += 366;
                }else {
                    totalDay += 365;
                }
            }
            totalDay++;
        }else if(year1<year2) {
            for (int i = month1 ; i <= 12 ; ++i ) {
                totalDay += mon_day[IsLeapYear(year1)][i] - day1;
                day1 = 0;
            }
            for (int j = 0; j < month2 ; ++j ) {
                totalDay += mon_day[IsLeapYear(year2)][j] + day2;
                day2 = 0;
            }
            for (int k = year1; k < year2-1; k++) {
                if (IsLeapYear(k)) {
                    totalDay += 366;
                }else {
                    totalDay += 365;
                }
            }
            totalDay++;
        }else {
            int tDay1 = 0,tDay2 = 0;
            for (int i = month1 ; i <= 12 ; ++i ) {
                tDay1 += mon_day[IsLeapYear(year1)][i] - day1;
                day1 = 0;
            }
            for (int i = month2 ; i <= 12 ; ++i ) {
                tDay2 += mon_day[IsLeapYear(year2)][i] - day2;
                day2 = 0;
            }
            tDay1-tDay2 > 0 ? totalDay = tDay1-tDay2+1 : totalDay = tDay2-tDay1+1;
        }
        printf("%d",totalDay);
    }
    return 0;
}

全部评论

相关推荐

06-15 02:05
已编辑
南昌航空大学 数据分析师
Eason三木:你如果想干技术岗,那几个发公众号合唱比赛的经历就去掉,优秀团员去掉,求职没用。然后CET4这种不是奖项,是技能,放到下面的专业技能里或者单独列一个英语能力。 另外好好改改你的排版,首行缩进完全没有必要,行间距好好调调,别让字和标题背景黏在一起,你下面说能做高质量PPT你得展现出来啊,你这简历排版我用PPT做的都能比你做的好。 然后自我评价,你如果要干数据工程师,抗压能力强最起码得有吧。
简历中的项目经历要怎么写
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 16:22
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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