LeetCode 题解 | 日期之间隔几天(模拟 C++和Python)

题目描述(简单难度)

原题链接
在这里插入图片描述

算法

(模拟)
这个题思路很简单,把日期都转换为和1970年1月1日间隔的天数,然后两个相减即可

用Python写几行就过了,不过这个题用C++写代码量很大,把月份设置为常量数组可以简化代码

C++代码1

class Solution {
public:
    const int months[12] = {31, 28, 31, 30, 31, 30, 31,  31, 30, 31, 30, 31};
    
    bool isLeap(int year) {
        return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));
    }
    
    vector<int> getYearMonthDay(string s) {
        vector <int> time(3, 0);
        time[0] = stoi(s.substr(0, 4)); // year
        time[1] = stoi(s.substr(5, 2)); // month
        time[2] = stoi(s.substr(8, 2)); // day
        return time;
    }
    
    int get(vector<int> &time) {
        int days = 0; 
        for (int i = 1970; i < time[0]; i ++) {
            days += 365;
            if (isLeap(i)) days += 1;
        }
        
        for (int i = 0; i < time[1] - 1; i ++) { // 2月10日 则加上一月份日期
            days += months[i];
        }
        
        if (isLeap(time[0]) && time[1] >= 3) days ++;   
        days += time[2];

        return days;
    }
    
    int daysBetweenDates(string date1, string date2) {
        vector<int> A = getYearMonthDay(date1);
        vector<int> B = getYearMonthDay(date2);
        int days1 = get(A), days2 = get(B);

        return abs(days1 - days2);
    }
};

C++代码2

这个代码是我在题解去看到的 传送门,用了sscanf函数使代码更加简洁,值得学习

class Solution {
public:
    #define intfabs(x) ((x)<0?-(x):(x))

    int isleap(int y) {
        return y % 4 == 0 && y % 100 != 0 || y % 400 == 0;
    }

    const int tab[13] = {-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    int getdate1(char* date) {
        int y, m, d, r = 0;
        sscanf(date, "%d-%d-%d", &y, &m, &d);

        for(int i = 1970; i < y; i++)
            if(isleap(i)) r += 366;
            else r += 365;

        for(int i = 1; i < m; i++) {
            r += tab[i];
            if(i == 2 && isleap(y)) r += 1;
        }

        r += d;
        return r;
    }

    int daysBetweenDates(string date1, string date2) {
        char dst1[30], dst2[30];
        
        // string转为char*
        strcpy(dst1,date1.c_str());
        strcpy(dst2,date2.c_str());

        return intfabs(getdate1(dst1) - getdate1(dst2));
    }
};

Python代码

datetime是Python处理日期和时间的标准库 datetime库使用参考

注意到datetime是模块,datetime模块还包含一个datetime类

import datetime
class Solution(object):
    def daysBetweenDates(self, date1, date2):
        date1=datetime.datetime.strptime(date1,"%Y-%m-%d")
        date2=datetime.datetime.strptime(date2,"%Y-%m-%d")
        num=(date1-date2).days
        return abs(num)

写在最后:我的博客主要是对计算机领域所学知识的总结、回顾和思考,把每篇博客写得通俗易懂是我的目标,分享技术和知识是一种快乐 ,非常欢迎大家和我一起交流学习,有任何问题都可以在评论区留言,也期待与您的深入交流(^∀^●)

发布了270 篇原创文章 · 获赞 111 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_43827595/article/details/104458551