2023.12.31每日一题

LeetCode每日一题

2023年的最后一题

1154.一年中的第几天

1154. 一年中的第几天 - 力扣(LeetCode)

描述

给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。

示例 1:

复制代码
输入:date = "2019-01-09"
输出:9
解释:给定日期是2019年的第九天。

示例 2:

复制代码
输入:date = "2019-02-10"
输出:41

提示:

  • date.length == 10
  • date[4] == date[7] == '-',其他的 date[i] 都是数字
  • date 表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日

思路

根据给出的date,获取年份(YYYY),月份(MM),天数(DD)

先按平年。即每年365天计算出每个月之前的天数,然后再判断年份是否为闰年,为闰年并且月份大于等于3,则在天数上加1.

代码

C++
C++ 复制代码
class Solution {
public:
    int dayOfYear(string date) {
        int year = getNum(0,4,date);
        int month = getNum(5,7,date);
        int day = getNum(8,10,date);

        // 每个月之前的总天数
        vector<int> daysBeforeMonth = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
        int days = daysBeforeMonth[month - 1] + day;
        if((year % 400 ==0 || (year % 4 == 0 && year % 100 != 0)) && month >= 3) days++;
        return days;
    }

    // 根据给定范围提取对应的数字
    int getNum(int start, int end , string date){
        int number = 0;
        for(int i = start; i < end; i++){
            number *= 10;
            number += date[i] - '0';
        }
        return number;
    }
};
Java

charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。

java 复制代码
class Solution {
    public int dayOfYear(String date) {
        int year = getNum(0,4,date);
        int month = getNum(5,7,date);
        int day = getNum(8,10,date);

        // 每月之前的总天数
        int[] daysBeforeMonth = new int[]{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
        int days = daysBeforeMonth[month - 1] + day;
        if((year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) && month >= 3) days++;
        return days;
    }

    public int getNum(int start,int end, String date){
        int number = 0;
        for(int i = start; i < end; i++){
            number *= 10;
            number += date.charAt(i) - '0';
        }
    return number;
    }
}
相关推荐
yongui4783420 小时前
基于深度随机森林(Deep Forest)的分类算法实现
算法·随机森林·分类
是苏浙20 小时前
零基础入门C语言之C语言实现数据结构之单链表经典算法
c语言·开发语言·数据结构·算法
橘颂TA20 小时前
【剑斩OFFER】算法的暴力美学——点名
数据结构·算法·leetcode·c/c++
MATLAB代码顾问1 天前
多种时间序列预测算法的MATLAB实现
开发语言·算法·matlab
高山上有一只小老虎1 天前
字符串字符匹配
java·算法
愚润求学1 天前
【动态规划】专题完结,题单汇总
算法·leetcode·动态规划
林太白1 天前
跟着TRAE SOLO学习两大搜索
前端·算法
ghie90901 天前
图像去雾算法详解与MATLAB实现
开发语言·算法·matlab
云泽8081 天前
从三路快排到内省排序:探索工业级排序算法的演进
算法·排序算法
weixin_468466851 天前
遗传算法求解TSP旅行商问题python代码实战
python·算法·算法优化·遗传算法·旅行商问题·智能优化·np问题