一年中的第几天
题目
一年中的第几天
思路分析
1.substr函数分割字符串,stoi函数将字符串转为十进制
stoi函数介绍
substr函数介绍
2.判断是否为闰年,如果是闰年,则二月的天数+1
代码
#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; }
力扣代码
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;} };