计算日期到天数转换
题目来源
牛客网:计算日期到天数转换
题目描述
根据输入的日期,计算是这一年的第几天。
保证年份为4位数且日期合法。
进阶:时间复杂度:O(n) ,空间复杂度:O(1)
输入描述
输入一行,每行空格分割,分别是年,月,日
输出描述
输入一行,每行空格分割,分别是年,月,日
示例1
输入
2012 12 31
输出
366
示例2
输入
1982 3 4
输出
63
思路分析
- 定义一个数组,保存一年12个月的天数,为了让月份和数组下标对应,将数组长定义为13,数组第一个元素不使用,仅作占位
- 获取天数的函数调用判断闰年的函数,如果为闰年,2月天数置为29
代码展示
#include <iostream>
using namespace std;
bool IsLeap(int year)
{
//闰年判断
if((year%4==0&&year%100!=0)||year%400==0)
{
return true;
}
return false;
}
int GetDayOfMonth(int year,int month)
{
//获取某一个月的天数
int tables[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(IsLeap(year))
{
tables[2]=29;
}
return tables[month];
}
int main(){
int year,month,day;
while(cin>>year>>month>>day)
{
int days=0;
for(int i=1;i<month;i++)
{
//注意第二个参数传i,不是month
days+=GetDayOfMonth(year,i);
}
days+=day;
cout<<days<<endl;
}
}