【跟着英雄学算法第⑥天】日期计算——附Leetcode刷题题解(C语言实现)

✨前言✨

       在这个系列中,博主准备分享每日在万人千题社区打卡学习的算法。博主也是小白,因此也很能理解新手在刷题时的困惑,所以关注博主,每天学习一道算法吧。同时也欢迎大家加入万人千题习活动,正所谓:一个人可以走的很快,但一群人才能走的更远。

万人千题打卡社区https://bbs.csdn.net/forums/hero?category=0&typeId=17913https://bbs.csdn.net/forums/hero?category=0&typeId=17913


目录

一、算法思想笔记

①闰年计算

②约瑟夫环思想

二、一周中的第几天

①问题呈现

②代码操练

 三、1154.一年中的第几天

①题目呈现

②代码操练

 四、课后作业


 一、算法思想笔记

①闰年计算

什么是闰年?可以被400整除的数是闰年,可以被4整除但不能被100整除的数也是闰年,因此我们可以写一个判断是否为闰年的函数

int is_leap(int year)
{
    if(year % 400 == 0 || year %4 == 0 && year % 100 != 0)
        return 1;
    else
        return 0;
}

②约瑟夫环思想

假设今天是星期5,那如何写代码判断10天后是星期几呢?

你可能首先想到的代码是这样的

(5+10)% 7  

掐指一算,诶还真的对。但上述思想的弊端在于(6+1)% 7  无法判断。所以我们想,要是星期从星期0开始多好啊,那就不会出问题了。你想的很对,没错我们只要让星期从“星期0”开始就可以

(day - 1 + △day)% 7 +1 

我们人为的让星期从0开始,只要最后加回去被我们减掉的一天即可

二、一周中的第几天

①问题呈现

1185. 一周中的第几天https://leetcode-cn.com/problems/day-of-the-week/https://leetcode-cn.com/problems/day-of-the-week/

 ②代码操练

int is_leap(int year)
{
    if(year % 400 == 0 || year %4 == 0 && year % 100 != 0)
        return 1;
    else
        return 0;
}
char * dayOfTheWeek(int day, int month, int year)
{
    int i = 0;
    int daysum = 0;
    int dayOfmonth[]={ 0 , 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 };
    char* ch[] = { "Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday" };
    for( i = 1971;i < year; i++)
    {
        daysum += is_leap( i ) ? 366 : 365;
    }
    for(i=1;i<month;i++)
    {
        daysum+=dayOfmonth[i];
    }
   daysum+=day;
   if(month > 2 && is_leap(year))
   {
       daysum++;
   }
    
  return ch[(3+daysum)%7];//约瑟夫环思想的体现
}

 三、1154.一年中的第几天

1154.一年中的第几天https://leetcode-cn.com/problems/day-of-the-year/icon-default.png?t=L9C2https://leetcode-cn.com/problems/day-of-the-year/

①题目呈现

 ②代码操练

int is_leap(int year)//判断是否为闰年
{
    if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)
        return 1;
    else
        return 0;
}

int strToint(char* date, int size)//字符串转数字函数
{
    int sum = 0;
    for (int i = 0; i < size; i++)
    {
        sum = sum * 10 + date[i] - '0';//注意这个'0'别忘记,想想为什么?
    }
    return sum;
}

int dayOfYear(char* date)
{
    int sumday = 0;
    int year = strToint(date + 0, 4);
    int month = strToint(date + 5, 2);
    int day = strToint(date + 8, 2);
    int monthday[] = { 0 , 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30, 31 };

    for (int i = 1; i < month; i++)
    {
        sumday += monthday[i];
    }
    sumday += day;
    if (month > 2 && is_leap(year))
    {
        sumday++;
    }

    return sumday;
}

 四、课后作业

(友情提示,就是上面两道题的结合)

1360. 日期之间隔几天https://leetcode-cn.com/problems/number-of-days-between-two-dates/icon-default.png?t=L9C2https://leetcode-cn.com/problems/number-of-days-between-two-dates/

Guess you like

Origin blog.csdn.net/whc18858/article/details/120990642