zoukankan      html  css  js  c++  java
  • 计算两个日期之间相隔的天数

    Q:给出两个日期,计算出两个日期相隔多少天。

    • 按闭区间来算,即,输出值大于等于2。
    • 难点主要在处理闰年,因为闰年关系到2月份究竟有几天。
    // C++11代码
    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <string>
    #include <algorithm>
    #include <vector>
    using namespace std;
    const int N = 110;
    
    int month[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    // 闰年需要改2月天数
    void SetLeapYear(int year)
    {
        if (year%100==0 && year%400==0) month[2] = 29;
        if (year%100==0 && year%400!=0) month[2] = 28;
        if (year%100!=0 && year%4==0)   month[2] = 29;
        if (year%100!=0 && year%4!=0)   month[2] = 28;
    }
    
    int main()
    {
        freopen("input.txt", "r", stdin);
        
        string date1, date2;
        while(cin>>date1>>date2)
        {
            int year1 = stoi(date1.substr(0, 4));
            int month1 = stoi(date1.substr(4, 2));
            int day1 = stoi(date1.substr(6, 2));
    
            int year2 = stoi(date2.substr(0, 4));
            int month2 = stoi(date2.substr(4, 2));
            int day2 = stoi(date2.substr(6, 2));
    
            // 相隔的年份[year1, year2) 左开右闭。这样就算多了year1中的部分月,算少了year2中的部分月
            int days = 0;
            for (int i=year1; i<year2; i++)
            {
                SetLeapYear(i);
                for (int j=1; j<13; j++)
                    days += month[j];
            }
    
            // 补上year2算少的部分
            SetLeapYear(year2);
            for (int j=1; j<month2; j++)
                days += month[j];
            days += day2;
    
            // 扣去year1多算的部分
            SetLeapYear(year1);
            for (int j=1; j<month1; j++)
                days -= month[j];
            days -= day1 - 1;
    
            printf("%d
    ", days);
        }
        return 0;
    }
    
  • 相关阅读:
    HackerRank savita-and-friends
    HackerRank training-the-army
    51Nod 1378 夹克老爷的愤怒
    51Nod 1380 夹克老爷的逢三抽一
    Codeforces 566 D. Restructuring Company
    BZOJ 2822: [AHOI2012]树屋阶梯
    Codeforces Gym 101138 G. LCM-er
    51Nod 1250 排列与交换
    BZOJ 1511: [POI2006]OKR-Periods of Words
    BZOJ 1355: [Baltic2009]Radio Transmission
  • 原文地址:https://www.cnblogs.com/xcw0754/p/8177901.html
Copyright © 2011-2022 走看看