题目描述:
输入日期格式:YYYYMMDD,求与20190205相隔天数。
样例输入:
输入:
20190208
输出:
3
思路:
这道题短小精悍,还是有点难度的。
用数组a[13][2]记录每月的天数,其中a[1][0]表示不是闰年时1月的天数, a[1][1]表示闰年时1月的天数。
然后根据数组中的数据作为进位的边界。
闰年:
闰年是公历中的名词。闰年分为普通闰年和世纪闰年。
普通闰年:公历年份是4的倍数的,且不是100的倍数,为普通闰年。(如2004年就是闰年);
世纪闰年:公历年份是整百数的,必须是400的倍数才是世纪闰年(如1900年不是世纪闰年,2000年是世纪闰年);
代码:
1.一开始的写法,很臭很长。
#include <cstdio>
#include <algorithm>
using namespace std;
int a[13][2]={{0,0},{31,31},{28,29},{31,31},{30,30},{31,31},{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}};
int isLeap(int year){
if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return 1;
else return 0;
}
int main(){
int time1 ;
scanf("%d", &time1);
int y1 = time1 / 10000;
int m1 = time1 % 10000 / 100;
int d1 = time1 % 100;
int count = 0;
while(y1 != 2019 || m1 != 2 || d1 != 5){
if(y1 == 2019){
if(m1 > 2){
if(d1 > 1){
d1--;
count++;
}else{
m1--;
d1 = a[m1][isLeap(y1)];
count++;
}
}else if(m1 < 2){
if(d1 < a[m1][isLeap(y1)]){
d1++;
count++;
}else{
m1++;
d1 = 1;
count++;
}
}else{
if(d1 < 5){
d1++;
count++;
}else if(d1 > 5){
d1--;
count++;
}else break;
}
}else if(y1 < 2019){
if(d1 < a[m1][isLeap(y1)]){
d1++;
count++;
}else{
if(m1 < 12){
d1 = 1;
m1++;
count++;
}else{
y1++;
m1=1;
d1=1;
count++;
}
}
}else{
if(d1 > 1){
d1--;
count++;
}else{
if(m1 > 1){
m1--;
d1 = a[m1][isLeap(y1)];
count++;
}else{
y1--;
m1 = 12;
d1 = a[m1][isLeap(y1)];
count++;
}
}
}
}
printf("%d", count);
return 0;
}
2.改进后
#include <cstdio>
#include <algorithm>
using namespace std;
int a[13][2]={{0,0},{31,31},{28,29},{31,31},{30,30},{31,31},{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}};
int isLeap(int year){
if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return 1;
else return 0;
}
int main(){
int time1 ;
int time2 = 20190205;
scanf("%d", &time1);
if(time1 > time2) swap(time1, time2);
int y1 = time1 / 10000;
int m1 = time1 % 10000 / 100;
int d1 = time1 % 100;
int y2 = time2 / 10000;
int m2 = time2 % 10000 / 100;
int d2 = time2 % 100;
int count = 0;
while(y1 < y2 || m1 < m2 || d1 < d2){
if(d1 < a[m1][isLeap(y1)]){
d1++;
count++;
}else{
if(m1 < 12){
m1++;
d1 = 1;
count++;
}else{
y1++;
d1 = 1;
m1 = 1;
count++;
}
}
}
printf("%d", count);
return 0;
}