【每周例题】力扣 C++ 一年中的第几天

一年中的第几天

题目

一年中的第几天

 思路分析

1.substr函数分割字符串,stoi函数将字符串转为十进制

stoi函数介绍

substr函数介绍

2.判断是否为闰年,如果是闰年,则二月的天数+1

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    int months[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
    string date;
    cin >> date;
     
    int year, month, day;
    year = stoi(date.substr(0, 4));
    month = stoi(date.substr(5, 2));
    day = stoi(date.substr(8, 2));
    //闰年
    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
    {
        months[2]++;
    }
 
    int sum = 0;
 
    for (int i = 1; i < month; i++)
    {
        sum += months[i];
    }
 
    cout << sum + day;
 
    return 0;
}

 力扣代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
    int dayOfYear(string date)
    {
        int months[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
        int year, month, day;
        year = stoi(date.substr(0, 4));
        month = stoi(date.substr(5, 2));
        day = stoi(date.substr(8, 2));
        //闰年
        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
        {
            months[2]++;
        }
 
        int sum = 0;
 
        for (int i = 1; i < month; i++)
        {
            sum += months[i];
        }
 
        return sum + day;
    }
};

  

posted @   山远尽成云  阅读(93)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示