美文网首页
日期差值

日期差值

作者: Bing_o_o | 来源:发表于2019-08-20 10:43 被阅读0次

问题描述

有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天

输入描述:

有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD

输出描述:

每组数据输出一行,即日期差值

示例

输入
20110412
20110422

输出
11

C++实现

#include <bits/stdc++.h>
using namespace std;

int day_of_month[13][2] = {
    {0, 0},
    {31, 31},
    {28, 29},
    {31, 31},
    {30, 30},
    {31, 31},
    {30, 30},
    {31, 31},
    {31, 31},
    {30, 30},
    {31, 31},
    {30, 30},
    {31, 31}
};

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

struct Date {
    int year;
    int month;
    int day;
    
    Date(int time) {
        year = time / 10000;
        month = time % 10000 / 100;
        day = time % 100;
    }
    
    void next() {
        day++;
        if(day == day_of_month[month][isLeap(year)] + 1) {
            day = 1;
            month++;
        }
        if(month == 13) {
            month = 1;
            year++;
        }
    }
    
    bool operator <(const Date &date) {
        int time1 = year * 10000 + month * 100 + day;
        int time2 = date.year * 10000 + date.month * 100 + date.day;
        return time1 < time2;
    }
};

int main() {
    
    int time1, time2;
    while(scanf("%d%d", &time1, &time2) != EOF) {
        if(time1 > time2) {
            int temp = time1;
            time1 = time2;
            time2 = temp;
        }
        
        Date date1(time1);
        Date date2(time2);
        
        int ans = 1;
        while(date1 < date2) {
            date1.next();
            ans++;
        }
        printf("%d\n", ans);
    }
    
    return 0;
} 

相关文章

网友评论

      本文标题:日期差值

      本文链接:https://www.haomeiwen.com/subject/olpusctx.html