牛客oj 习题2.7Day Of Week&&习题2.8日期类(Map)

这题必须清楚第一个星期一是0001年1月1号,所以求星期几就是从0001年1月1号到当前日期再%7,余的过程有技巧。

剩下的就是对字符串的处理了我这里用了Map。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <map>

using namespace std;

map<string, int> Month;
map<int, string> Week;

int table[2][13] = {
	{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
	{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

bool IsLeapYear(int year){
	if((year%400 == 0) || (year%100 != 0 && year%4 == 0)) return true;
	return false;
}

int NumberOfYear(int year){
	if(IsLeapYear(year)) return 366;
	else return 365;
}

void Initiate(){
	Month["January"] = 1;
	Month["February"] = 2;
	Month["March"] = 3;
	Month["April"] = 4;
	Month["May"] = 5;
	Month["June"] = 6;
	Month["July"] = 7;
	Month["August"] = 8;
	Month["September"] = 9;
	Month["October"] = 10;
	Month["November"] = 11;
	Month["December"] = 12;
	Week[0] = "Sunday";
	Week[1] = "Monday";
	Week[2] = "Tuesday";
	Week[3] = "Wednesday";
	Week[4] = "Thursday";
	Week[5] = "Friday";
	Week[6] = "Saturday";
}


int main(){
//	freopen("in.txt", "r", stdin);
	Initiate();
	int d, y;
	string M;
	while(cin >> d >> M >> y){
		int day = d;
		int month = Month[M];
		int year = y;
		int number = day;
		int row = IsLeapYear(year);
		for(int i = 0; i < month; i++){
			number += table[row][i];
		}
		while(--year){
			number += NumberOfYear(year);
			number %= 7;
		}
		cout << Week[number] << endl;
	}
	return 0;
}

这题加一天有可能改变年份,所以先根据日期得出天数,然后根据天数反推出日期。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <map>

using namespace std;

int table[2][13] = {
	{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
	{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

bool IsLeapYear(int year){
	if((year%400 == 0) || (year%100 != 0 && year%4 == 0)) return true;
	return false;
}

int NumberOfYear(int year){
	if(IsLeapYear(year)) return 366;
	else return 365;
}

int main(){
//	freopen("in.txt", "r", stdin);
	int m, year, month, day, number;
	scanf("%d", &m);
	while(m--){
		scanf("%d %d %d", &year, &month, &day);
		number = day;
		int row = IsLeapYear(year);
		for(int i = 0; i < month; i++){
			number += table[row][i];
		}
		number++;
		if(number > NumberOfYear(year)){
			year++;
			number -= NumberOfYear(year);
		}
		row = IsLeapYear(year);
		month = 1;
		while(number > table[row][month]){
			number -= table[row][month];
			month++;
		}
		day = number;
		printf("%02d-%02d-%02d\n", year, month, day);
	}
	return 0;
}
发布了411 篇原创文章 · 获赞 72 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/Flynn_curry/article/details/104362456