【每周例题】力扣 C++ 一年中的第几天
一年中的第几天
题目
思路分析
1.substr函数分割字符串,stoi函数将字符串转为十进制
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; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现