描述
根据输入的日期,计算是这一年的第几天。
保证年份为4位数且日期合法。
进阶:时间复杂度:O(n)\O(n)?,空间复杂度:O(1)\O(1)?
输入描述:
输入一行,每行空格分割,分别是年,月,日
输出描述:
输出是这一年的第几天
示例1
输入:
2012 12 31
复制输出:
366
复制
示例2
输入:
1982 3 4
复制输出:
63
#include <iostream>
//2012 12 31
int date2day(std::string date)
{
int count = 0;
int len = date.length();
// std::cout << date << std::endl;
int index = date.find(' ');
int year = atoi(date.substr(0, index).c_str());
date = date.substr(index + 1, len - index - 1);
index = date.find(' ');
int month = atoi(date.substr(0, index).c_str());
date = date.substr(index + 1, len - index - 1);
index = date.find(' ');
int day = atoi(date.substr(0, index).c_str());
if((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0))
{
switch (month)
{
case 1:
count = day;
break;
case 2:
count = day + 31;
break;
case 3:
count = day + 60;
break;
case 4:
count = day + 91;
break;
case 5:
count = day + 121;
break;
case 6:
count = day + 152;
break;
case 7:
count = day + 182;
break;
case 8:
count = day + 213;
break;
case 9:
count = day + 244;
break;
case 10:
count = day + 274;
break;
case 11:
count = day + 305;
break;
case 12:
count = day + 335;
break;
default:
break;
}
}
else
{
switch (month)
{
case 1:
count = day;
break;
case 2:
count = day + 31;
break;
case 3:
count = day + 59;
break;
case 4:
count = day + 90;
break;
case 5:
count = day + 120;
break;
case 6:
count = day + 151;
break;
case 7:
count = day + 181;
break;
case 8:
count = day + 212;
break;
case 9:
count = day + 243;
break;
case 10:
count = day + 273;
break;
case 11:
count = day + 304;
break;
case 12:
count = day + 334;
break;
default:
break;
}
}
return count;
}
int main()
{
std::string date;
while(getline(std::cin, date))
{
std::cout << date2day(date) << std::endl;
}
return 0;
}
|