题解 | #日期差值#
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <iostream> using namespace std; const int year1[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; const int year2[12] = {31,29,31,30,31,30,31,31,30,31,30,31}; const int days1 = 365; const int days2 = 366; int getYear(int date){ return date / 10000; } int getMonth(int date){ return (date - 10000 * getYear(date)) / 100; } int getDay(int date){ return date - getYear(date)*10000 - getMonth(date) * 100; } int getSum(int date){ int y = getYear(date); int m = getMonth(date); int d = getDay(date); int ret = 0; if((y % 400 == 0) || (y % 4 == 0 && y % 100 != 0)){ for(int i = 1;i<m;i++){ ret += year2[i - 1]; } }else{ for(int i = 1;i<m;i++){ ret += year1[i - 1]; } } return ret + d; } int get_diff(int date1,int date2){ int y1 = getYear(date1); int y2 = getYear(date2); int m1 = getMonth(date1); int m2 = getMonth(date2); int d1 = getDay(date1); int d2 = getDay(date2); int ret = 0; if(y1 < y2){ //先加上今年剩余的天数 if((y1 % 400 == 0) || (y1 % 4 == 0 && y1 % 100 != 0)) ret += (366 - getSum(date1) + 1); else ret += (365 - getSum(date1) + 1); y1++; }else{ if(m1 < m2){ if((y1 % 400 == 0) || (y1 % 4 == 0 && y1 % 100 != 0)) ret += (year2[m1 - 1] - d1 + 1); else ret += (year1[m1 - 1] - d1 + 1); m1++; }else{ return d2 - d1 + 1; } while(m1 < m2){ if((y1 % 400 == 0) || (y1 % 4 == 0 && y1 % 100 != 0)){ ret += year2[m1 - 1]; }else{ ret += year1[m1 - 1]; } m1++; } return ret + d2; } while(y1 < y2){ if((y1 % 400 == 0) || (y1 % 4 == 0 && y1 % 100 != 0)) ret += 366; else ret += 365; y1++; } return ret + getSum(date2); } int main() { int a, b; while (cin >> a >> b) { // 注意 while 处理多个 case if(a > b) cout << get_diff(b, a) << endl; cout << get_diff(a, b) << endl; } return 0; }