题解 | #日期差值#

日期差值

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

从0年开始算是第几天,然后相减

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;

int daytab[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 isLeapYear(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int main()
{
    int i, j, number1 = 0, number2 = 0, row;
    string str1, str2;
    cin >> str1 >> str2;
    int year1 = stoi(str1.substr(0, 4));  // str1[0~3]
    int year2 = stoi(str2.substr(0, 4));  // str2[0~3]
    int month1 = stoi(str1.substr(4, 2)); // str1[4~5]
    int month2 = stoi(str2.substr(4, 2)); // str2[4~5]
    int day1 = stoi(str1.substr(6, 2));   // str1[6~7]
    int day2 = stoi(str2.substr(6, 2));   // str2[6~7]
    row = isLeapYear(year1);
    for (i = 0; i < month1; i++)
    {
        number1 += daytab[row][i];
    }
    number1 += day1;
    for (i = 0; i < year1; i++)
    {
        row = isLeapYear(i); // 0是平年,1是闰年
        if (row == 0)
            number1 += 365;
        else
            number1 += 366;
    }

    row = isLeapYear(year2);
    for (i = 0; i < month2; i++)
    {
        number2 += daytab[row][i];
    }
    number2 += day2;
    for (i = 0; i < year2; i++)
    {
        row = isLeapYear(i); // 0是平年,1是闰年
        if (row == 0)
            number2 += 365;
        else
            number2 += 366;
    }
    int result = number1 - number2;
    // for (i = year1; i < year2; i++)
    // {
    //     row = isLeapYear(i); // 0是平年,1是闰年
    //     if (row == 0)
    //         result += 365;
    //     else
    //         result += 366;
    // }
    result = abs(result);
    result++;
    cout << result << endl;

    return 0;
}

全部评论

相关推荐

05-23 20:31
已编辑
武汉大学 Java
内向的柠檬精在研究求职打法:注意把武大标粗标大 本地你俩不是乱杀
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务