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

解决牛客oj中关于日期和星期的算法问题,重点在于理解从0001年1月1日开始的天数与星期之间的关系,并使用Map进行字符串处理。考虑到日期加一天可能跨越年份,需先计算总天数再反推日期。
摘要由CSDN通过智能技术生成

 

这题必须清楚第一个星期一是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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值