杭电oj 1201 AC代码(利用字符串解决)
using namespace std;
#include<iostream>
bool leapyear(int x)
{
if((x%4 == 0&&x%100 != 0)||(x%100 == 0&&x%400 == 0))
return true;
else
return false;
}
int getyear(char *a)
{ int year=0;
for(int i=0;i<=3;i++)
{
year*=10;
year=year+int(a[i]-48);
}
return year;
}
int main()
{
int T,sum_day = 6570,year1=0,year2=0;
char borndate[11];
cin>>T;
while(T--)
{
int addday=0;
cin>>borndate;
year1 = getyear(borndate);
year2 = year1+18;
if(borndate[5]=='0'&&borndate[6]=='2'&&borndate[8]=='2'&&borndate[9]=='9')//2月29出生,则18岁无生日;
{
cout<<"-1"<<endl;
}
else if(leapyear(year1)==false&&leapyear(year2) == false)//出生在非闰年,18岁生日非闰年
{
for(int i=year1+1;i<year2;i++)
if(leapyear(i))
addday++;
cout<<sum_day+addday<<endl;
}
else if(leapyear(year1)==true&&leapyear(year2)==false)//出生在闰年,18岁生日为非闰年
{
for(int i=year1+1;i<year2;i++)
if(leapyear(i))
addday++;
if(borndate[6]>='3'||borndate[5]=='1')
cout<<sum_day+addday<<endl;
if(borndate[6]<'3'&&borndate[5]=='0')
cout<<sum_day+addday+1<<endl;
}
else if(leapyear(year1)==false&&leapyear(year2)==true)//出生在非闰年,18岁生日为闰年
{
for(int i=year1+1;i<year2;i++)
if(leapyear(i))
addday++;
if(borndate[6]>='3'||borndate[5] == '1')
cout<<sum_day+addday+1<<endl;
if(borndate[6]<'3'&&borndate[5]=='0')
cout<<sum_day+addday<<endl;
}
}
return 0;
}
利用出生年份与18岁年份是否为闰年关系来探讨,可以得到三种不同情况 非闰-非闰,闰-非闰,非闰-闰,不要漏掉为出生于2.29日的情况。