题解 | #日期差值#

日期差值

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

#include<cstdio>
#include<string>

using namespace std;

void convertDate(char arr[9], int& year, int& month, int& day) {//先转换日期
    year = (arr[0] - '0') * 1000 + (arr[1] - '0') * 100 + (arr[2] - '0') * 10 +
           (arr[3] - '0');
    month = (arr[4] - '0') * 10 + (arr[5] - '0');
    day = (arr[6] - '0') * 10 + (arr[7] - '0');
}

int daytab[13] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

bool isLeapYear(int year) { //判断是否为闰年
    if ((year % 4 == 0 && year & 100 != 0) || year & 400 == 0) {
        daytab[1] = 29;
        return true;
    } else {
        daytab[1] = 28;
        return false;
    }
}

int dayNumber(int year, int month, int day) { //判断此日期据元旦有几天
    int ret = day;
    isLeapYear(year);
    while (--month) {
        ret += daytab[month - 1];
    }
    return ret;
}

int main() {
    char a[9], b[9];
    while (scanf("%s%s", a, b) != EOF) {
        int year1 = 0, month1 = 0, day1 = 0, year2 = 0, month2 = 0, day2 = 0;
        int ret = 0;
        convertDate(a, year1, month1, day1);
        convertDate(b, year2, month2, day2);
        if (year1 > year2) { //分开算,年份不同和年份相同思路不同
            ret += dayNumber(year1, month1, day1) - dayNumber(year2, month2, day2);
            while (year1 != year2) {
                ret += isLeapYear(year1 - 1) ? 366 : 365;
                year1--;
            }
        } else if (year1 < year2) {
            ret += dayNumber(year2, month2, day2) - dayNumber(year1, month1, day1);
            while (year1 != year2) {
                ret += isLeapYear(year2 - 1) ? 366 : 365;
                year2--;
            }
        } else {
            ret = abs(dayNumber(year1, month1, day1) - dayNumber(year2, month2, day2));
        }
        printf("%d\n", ret + 1);
    }
    return 0;
}

渣渣手法,与各位道友互相学习互相交流

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务