算法笔记练习 3.4 日期处理 问题 B: 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.

样例输入

21 December 2012
5 January 2013

样例输出

Friday
Saturday

思路

以 2012 年 12 月 16 日(星期日)为基准计算,假设公元 0 年 1 月 1 日是第 1 天,那么 2012 年 12 月 16 日是第 734853 天,再计算出输入的日期是第sum天。

令数字 0 代表星期日,数字 1 ~ 6 代表星期一到星期六,那么:

  1. 如果sum >= 734853,则答案就是(sum - 734853) % 7
  2. 如果sum < 734853,则答案就是(7 - (734853 - sum) % 7) % 7

代码

#include 
#include 
#define MAX 10
#define BASE 734853		// == totalday(2012,12,16) which is Sunday

const char engMonth[12][MAX] = {"January","February","March","April","May","June",
					 "July","August","September","October","November","December"};
const char engDay[7][MAX] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}; 
const int common[12]	= {31,28,31,30,31,30,31,31,30,31,30,31};
const int leap[12] 		= {31,29,31,30,31,30,31,31,30,31,30,31};

int isLeap(int n) {
	int yes = 0;
	if (!(n % 400))
		yes = 1;
	else if (!(n % 100))
		yes = 0;
	else if (!(n % 4))
		yes = 1;
	else
		yes = 0;
	return yes;
} 
int totalDay(int y, int m, int d) {
	int sum = 0;
	int i;
	for (i = 1; i < y; ++i) {
		if (isLeap(i))
			sum += 366;
		else
			sum += 365;
	}
	for (i = 1; i < m; ++i) {
		if (isLeap(y)) 
			sum += leap[i - 1];
		else
			sum += common[i - 1]; 
	}
	sum += d;
	return sum;
} 
int getMonth(char *mon) {
	int m = 0, i;
	for (i = 0; i < 12; ++i) {
		if (!strcmp(mon,engMonth[i])) {
			m = i + 1;
			break;
		} 
	} 
	return m;
} 

int main() {
	int d, m, y, sum, week;
	char mon[MAX];
	while (scanf("%d %s %d", &d, mon, &y) != EOF) {
		m = getMonth(mon);
		sum = totalDay(y,m,d);
		if (sum >= BASE)
			week = (sum - BASE) % 7;
		else
			week = (7 - (BASE - sum) % 7) % 7;
		puts(engDay[week]);
	} 
	return 0;
} 

你可能感兴趣的:(算法笔记)