C++日期差值问题(2个日期之间差几天)

上面是牛客网给出的题目。

思路

假设第一个输入的日期为2011 12 03,第二个输入的日期为2024 02 29。

这两个日期并不相等,我们可以让日期2011 12 03一直加1,直到等于2024 02 29为止。

在这个过程中,每+1一次,就让ret记录一次。

最后ret就是我们要的差值。

代码

首先我们要编写一个日期类,

这个类实现了+=,>,==,!=的重载,然后才能轻松编写上面思路的代码,

我的一篇博客讲了这个日期类的实现:http://t.csdnimg.cn/SMo8g

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

class Date{
    public:
    Date(int y, int m, int d):
    _year(y),
    _month(m),
    _day(d){}
    int GetMonthDay(int year,int month)
    {
        static int a[13]={-1,31,28,31,30,31,30,31,31,30,31,30,31};
        if((month==2)&&((year%400==0)||(year%4==0&&year%100!=0)))
        {
            return 29;
        }
        return a[month];
    }
    Date& operator+=(int day)
    {
        _day+=day;
        while(_day>GetMonthDay(_year, _month))
        {
            _day-=GetMonthDay(_year, _month);
            ++_month;
            if(_month==13)
            {
                _month=1;
                ++_year;
            }
        }
        return *this;
    }

    bool operator>(const Date&d)
    {
        if(_year>d._year)
        {
            return true;
        }
        else if (_year==d._year&&_month>d._month) {
            return true;
        }
        else if (_month==d._month&&_day>d._day) {
            return true;
        }
        return false;
    }

    bool operator==(const Date&d)
    {
        return (_year==d._year)&&(_month==d._month)&&(_day==d._day);
    }

    bool operator!=(const Date&d)
    {
        return !(*this==d);
    }

    int operator-(const Date&d)
    {
        Date min=*this;
        Date max=d;
        if(*this>d)
        {
            min=d;
            max=*this;
        }

        int ret=1;
        while(min!=max)
        {
            min+=1;
            ++ret;
        }
        return ret;
    }
    private:
    int _year;
    int _month;
    int _day;
};

int main() {
    int y1,y2,m1,m2,d1,d2;
    scanf("%4d%2d%2d",&y1,&m1,&d1);
    scanf("%4d%2d%2d",&y2,&m2,&d2);
    Date date1(y1,m1,d1);
    Date date2(y2,m2,d2);
    cout<<date1-date2<<endl;
}
// 64 位输出请用 printf("%lld")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值