题解 | #日期差值#
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <algorithm> #include <iostream> using namespace std; void swap(int a, int b) { int temp = a; a = b; b = temp; } int main() { int a, b; int year, month, day; int year2, month2, day2; int arr1[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int arr2[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; while (cin >> a >> b) { // 注意 while 处理多个 case if (b < a) { swap(a, b); } day = a % 100; month = (a / 100) % 100; year = (a / 10000); day2 = b % 100; month2 = (b / 100) % 100; year2 = (b / 10000); int sum = 0; int a = year; if (year2 - year) { int a = ++year; for (int i = a; i < year2; i++) { if ((a % 4 == 0 && a % 100 != 0) || (a % 400 == 0)) { sum += 366; } else { sum += 365; } } a = year; if ((a % 4 == 0 && a % 100 != 0) || (a % 400 == 0)) { for (int i = month; i < 12; i++) { sum += arr2[i]; } sum += (arr2[month-1] - day + 1); } else { for (int i = month; i < 12; i++) { sum += arr1[i]; } sum += (arr1[month-1] - day + 1); } a = year2; if ((a % 4 == 0 && a % 100 != 0) || (a % 400 == 0)) { for (int i = 0; i < month2 - 1; i++) { sum += arr2[i]; } sum += day2; } else { for (int i = 0; i < month2 - 1; i++) { sum += arr1[i]; } sum += day2; } } else { if ((a % 4 == 0 && a % 100 != 0) || (a % 400 == 0)) { for (int i = month ; i < month2 - 1; i++) { sum += arr2[i]; } if (month2 != month) { sum +=arr2[month]-day+1; sum +=day2; } else { sum = day2 - day + 1; } } else { for (int i = month ; i < month2 - 1; i++) { sum += arr1[i]; } } } cout << sum << endl; } } // 64 位输出请用 printf("%lld")
思路解析:
先处理数据,比较大小后分配大的时间和小的时间,然后数据分为年月日三个,
首先想到将日期差分为三段各自计算加起来,第一段是较小年份的后半段,第二段是中间相隔年份,第三段是较大年份的前半段,
- 计算中间年份比较简单,闰年与非闰年差1天;
- 计算较小年份的后半段:将当年的最后一天减去当天日期,分两步,计算此日期当月之后的月份,然后计算当月剩余日期,记得加1
- 计算较大年份的前半段:将此日期减去当年的第一天,分两步,计算此日期当月之前的月份,然后计算当月所占日期。
如果两日期为同一年
计算两日期之差,也是分三段,第一段计算两月之间的月份时间,第二段小月份后半段所剩的时间,第三段大月份所占的日期,若此时同月:则sum等于大日期的day减去小日期的day再加1,