【模板】日期类 (Day of Week题解)

适用范围:

(1)计算两个日期相差多少天。

(2)某天是星期几。

(3)几天后是日期是什么。

主要思路:构造Date类,初始化计算出每天到某个日期的天数差值。然后根据实际情况进一步处理。如(1)直接相减,(2)与已知的某天的天数差值对7取模,(3)循环适用nextDay()函数。

注意点:

(1)闰年的判断是:年份被4整除且不被100整除,或者被400整除。

(2)闰月的处理,nextDay()函数的处理。

(3)取模时候的处理。

(4)buf[]的Hash思想。

Day of Week

来源:王道论坛

题目描述

We now use the Gregorian style of dating in Russia. The leap years are years with number divisible by 4 but not divisible by 100, or divisible by 400. For example, years 2004, 2180 and 2400 are leap. Years 2004, 2181 and 2300 are not leap. Your task is to write a program which will compute the day of week corresponding to a given date in the nearest past or in the future using today’s agreement about dating.

输入描述:

There is one single line contains the day number d, month name M and year number y(1000≤y≤3000). The month name is the corresponding English name starting from the capital letter.

输出描述:

Output a single line with the English name of the day of week corresponding to the date, starting from the capital letter. All other letters must be in lower case.

Month and Week name in Input/Output: January, February, March, April, May, June, July, August, September, October, November, December Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

输入

9 October 2001
14 October 2001

输出

Tuesday
Sunday
#include<iostream>
#include<cstring>
#define isLeap(x) (x%400==0)||(x%4==0 && x%100!=0)
using namespace std;
int dayOfMonth[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 };
char monthName[13][20] = {
	"","January","Febuary","March","April","May","June",
	"July","August","September","October","November","December" };
char weekdayName[8][20] = {
	"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","" };
struct Date {
	int year, month, day;
	void nextDay() {
		day++;
		if (day > dayOfMonth[month][isLeap(year)]) {
			month++; day = 1;
			if (month > 12) {
				year++; month = 1;
			}
		}
	}
};
int buf[3010][13][32];
void init() {
	Date date;
	int count = 0;
	for (date.year = 0, date.month = 1, date.day = 1; date.year < 3001;) {
		buf[date.year][date.month][date.day] = count;
		count++;
		date.nextDay();
	}
}
int main(void)
{
	init();
	int day, year; char monthStr[20];
	while (cin >> day >> monthStr >> year) {
		int month;
		for (int i = 0; i < 13; i++) {
			if (0 == strcmp(monthStr, monthName[i])) {
				month = i; break;
			}
		}
		//14/10/2001 Sunday
		int gap = buf[year][month][day] - buf[2001][10][14];
		//cout<<gap<<endl; 
		gap = (gap % 7 + 7) % 7;
		cout << weekdayName[gap] << endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值