题解 | #日期差值#
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <iostream> #include <cstdio> using namespace std; int daytable[2][13]={ {31,28,31,30,31,30,31,31,30,31,30,31}, {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); //如果是闰年返回1,否则返回0 } int NumberOfYear(int year){ if(IsLeapYear(year)){ return 366; }else{ return 365; } } //获取年份 int getyear(int num){ return num/10000; } //获取月份 int getmonth(int num){ return (num%10000)/100; } //获取日期 int getday(int num){ return (num%10000)%100; } int main(){ int num1,num2; while(cin>>num1>>num2){ if (num1>num2) swap(num1,num2); //始终保持较小的为num1较大的为num2 int year1,year2,month1,month2,day1,day2; year1=getyear(num1); year2=getyear(num2); month1=getmonth(num1); month2=getmonth(num2); day1=getday(num1); day2=getday(num2); int row=IsLeapYear(year1); int days1=0; //num1对应的是当年第几天 for(int j=0;j<month1-1;j++){ days1+=daytable[row][j]; } days1+=day1; // cout<<days1<<endl; row=IsLeapYear(year2); int days2=0; //num2对应的是当年第几天 for(int j=0;j<month2-1;j++){ days2+=daytable[row][j]; } days2+=day2; // cout<<days2<<endl; int finalday=0; for(int i=year1;i<year2;i++){ finalday+=NumberOfYear(i); // cout<<finalday<<endl; } finalday+=(days2-days1+1); // cout<<year1<<' '<<year2<<endl; // cout<<month1<<' '<<month2<<endl; // cout<<day1<<' '<<day2<<endl; cout<<finalday<<endl; } return 0; }