题解 | #计算日期到天数转换#
计算日期到天数转换
http://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded
题目的主要信息:
根据输入的日期,计算是这一年的第几天。保证年份为4位数且日期合法。
方法一:
首先用数组monthday保存十二个月的对应的天数,首先判断当前年份是否为闰年,如果是闰年的话二月份有29天,然后遍历一遍月份天数,统计到当前月份的天数,然后加上当前月的天数即得到总天数。
具体做法:
#include <iostream>
using namespace std;
int main(){
int year,month,day;
cin>>year>>month>>day;
int count=0;//统计天数
int monthday[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};//monthday[i]表示第i月的天数
if(year%400==0||(year%4==0&&year%100!=0)){//当前月份大于两个月且为闰年时,二月有29天
monthday[2]=29;
}
for(int i=1;i<=month-1;i++){//统计到当前月份的天数
count=count+monthday[i];
}
count=count+day;//加上当前月的天数
cout<<count;
}
复杂度分析:
- 时间复杂度:,for循环的时间为常数时间。
- 空间复杂度:,monthday的大小为常数。
方法二:
整体思路和方法一相同,优化掉了循环。用数组num保存每个月结束对应的天数,即num[i]表示i+1月结束或i+2月前有num[i]天。首先判断当前年份是否为闰年,如果是闰年的话二月份有29天。然后对月份进行判断,如果是闰年且超过2月就要加上一天。
具体做法:
#include<iostream>
#include<string>
using namespace std;
int main(){
int year,month,day;
int res;
int flag=0;
int num[12]={31,59,90, 120, 151, 181, 212, 243, 273, 304, 334, 365};//num[i]表示第i+1个月结束后的天数
while(cin>>year>>month>>day){
if(year%4==0 && year%100!=0){//如果是闰年
flag=1;
}
if(month<=2){
if(month == 1){
res = day;
}else{
res = num[0] + day;
}
}else{//超过2月就要考虑是否为闰年了
res=num[month-2]+day+flag;
}
flag=0;
cout<<res<<endl;
}
}
复杂度分析:
- 时间复杂度:,直接计算只需常数时间。
- 空间复杂度:,数组num的大小为常数。