HDU 1201(18岁生日)

基础题。注意两个结点:出生在2.29之前,且当年为闰年;出生在2.29之后,且18岁那年为闰年。这两种情况下对应年份的闰年有效,在总天数上加1;否则即使这两年是闰年,也不能增加总天数。

#include <iostream>
#include <cstring>
#include <string>
using namespace std;

//判断x是否是闰年
bool isLeap(int x)
{
	if ((x % 4 == 0 && x % 100 != 0) || x % 400 == 0)
		return true;
	else
		return false;
}

int main()
{
	int T;
	cin >> T;
	string s; //日期字符串
	int year, month, day; //年,月,日
	while (T--)
	{
		cin >> s;
		year = (s[0] - '0') * 1000 + (s[1] - '0') * 100 + (s[2] - '0') * 10 + (s[3] - '0');
		month = (s[5] - '0') * 10 + (s[6] - '0');
		day = (s[8] - '0') * 10 + (s[9] - '0');

		if (month == 2 && day == 29 && isLeap(year + 18) == false) //没有18岁生日
		{
			cout << -1 << endl;
			continue;
		}

		int totalLeap = 0; //闰年数量
		for (int i = year + 1; i < year + 18; i++)
		{
			if(isLeap(i))
				++totalLeap;
		}
		if (month <= 2 && isLeap(year)) //出生在2.29之前,且当年为闰年
			++totalLeap;
		if (month > 2 && isLeap(year + 18)) ////出生在2.29之后,且18岁那年为闰年
			++totalLeap;

		cout << 18 * 365 + totalLeap << endl;
	}
	return 0;
}

继续加油。

发布了138 篇原创文章 · 获赞 1 · 访问量 7010

猜你喜欢

转载自blog.csdn.net/Intelligence1028/article/details/104606649
hdu