做差值
class Solution {
public:
int month[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int daysBetweenDates(string date1, string date2) {
return abs(get(date1)-get(date2));
}
int get(string date)
{
int res=0,year,mon,day;
sscanf(date.c_str(),"%d-%d-%d",&year,&mon,&day);
for(int i=1971;i<year;i++) res+=365+isleap(i);
for(int i=1;i<mon;i++)
{
if(i==2) res+=28+isleap(year);
else res+=month[i];
}
cout<<res+day<<endl;
return res+day;
}
bool isleap(int x)
{
return (x%400==0)||x%4==0&&x%100;
}
};
暴力加
class Solution {
public:
int month[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}};
int daysBetweenDates(string date1, string date2) {
int ans=0,n1,n2,y1,y2,r1,r2;
if(date1>date2) swap(date1,date2);
sscanf(date1.c_str(),"%d-%d-%d",&n1,&y1,&r1);
sscanf(date2.c_str(),"%d-%d-%d",&n2,&y2,&r2);
while(n1<n2||y1<y2||r1<r2)
{
r1++;
int maxr=month[is(n1)][y1];
if(r1>maxr)
{
r1=1;
y1++;
}
if(y1>12)
{
y1=1;
n1++;
}
ans++;
}
return ans;
}
bool is(int x)
{
return (x%400==0)||(x%4==0&&x%100);
}
};