[leetcode]5169. 日期之间隔几天

在这里插入图片描述

不调库

class Solution {
public:
    int daysBetweenDates(string date1, string date2) {
        int year1 = stoi(date1.substr(0,4));
        int month1 = stoi(date1.substr(5,2));
        int day1 = stoi(date1.substr(8,2));
        int year2 = stoi(date2.substr(0,4));
        int month2 = stoi(date2.substr(5,2));
        int day2 = stoi(date2.substr(8,2));
        
        int days[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 res = 0;
        if(year1 > year2 || (year1 == year2 && month1 > month2) || (year1 == year2 && month1 == month2 && day1 > day2))
        {
            swap(year1,year2);
            swap(month1,month2);
            swap(day1,day2);
        }
        for(int i = year1; i < year2; i++)
        {
            if((i%4 == 0 && i % 100 != 0 ) || (i % 400 == 0))
            {
                res += 366;
            }
            else
            {
                res += 365;
            }
        }
        
        bool flag = (year2%4 == 0 && year2 % 100 != 0 ) || (year2 % 400 == 0);
        for(int i = 1; i < month2; i++)
        {
            res += days[flag][i];
        }
        //cout<<res<<endl;
        res += day2;
        //cout<<res<<" "<<day2<<endl;
        flag = (year1%4 == 0 && year1 % 100 != 0 ) || (year1 % 400 == 0);
        for(int i = 1; i < month1; i++)
        {
            res -= days[flag][i];
        }
        //cout<<res;
        res -= day1;
        return res;
    }
};

调库:

class Solution {
public:
    int daysBetweenDates(string date1, string date2) {
        int year1 = stoi(date1.substr(0,4));
        int month1 = stoi(date1.substr(5,2));
        int day1 = stoi(date1.substr(8,2));
        int year2 = stoi(date2.substr(0,4));
        int month2 = stoi(date2.substr(5,2));
        int day2 = stoi(date2.substr(8,2));
        

        
        struct tm a = {0};
        struct tm b = {0};
        
        a.tm_year = year1 - 1900; //tm_year等于实际年份-1900
        a.tm_mon = month1 - 1;//tm_mon:0 1 2 3 4 5 6 7 8 9 10 11 从0开始
        a.tm_mday = day1;
        b.tm_year = year2 - 1900;
        b.tm_mon = month2 - 1;        
        b.tm_mday = day2;
        
        double second = difftime(mktime(&b),mktime(&a));
        
        return abs(second)/(24*60*60);
    }
};
发布了179 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40691051/article/details/104462220