Leetcode 1154.一年中的第几天

题目地址

思路

首先创建一个数组,每个元素的值为该月的天数。此时将二月的天数设置为28天。
然后根据是否为闰年,对二月份的天数决定是否需要+1。

然后就是计算天数和并返回结果。

代码实现(C++)

class Solution {
    
    
public:
    int dayOfYear(string date) 
    {
    
    
        int year=stoi(date.substr(0,4));
        int month=stoi(date.substr(5,2));
        int day=stoi(date.substr(8,2));
        int length[]={
    
    31,28,31,30,31,30,31,31,30,31,30,31};
        if(year%400==0||(year%4==0&&year%100!=0))
        {
    
    
            length[1]++;
        }
        int res=0;
        for(int i=0;i<month-1;i++)
        {
    
    
            res+=length[i];
        }
        res+=day;
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45847364/article/details/122059480