题解 | #Day of Week#
Day of Week
http://www.nowcoder.com/practice/a3417270d1c0421587a60b93cdacbca0
知识点
- STL的map的使用(也可以用switch-case,如果弄不明白map的话)
- 日期和星期的转换
- 根据题目给的测试样例确定余数和星期的对应关系
map用法
map<string,int> monthTable;
这是创建Map。
monthTable.insert(pair<string,int>("January",1)); monthTable.insert(pair<string,int>("February",2)); monthTable.insert(pair<string,int>("March",3)); monthTable.insert(pair<string,int>("April",4)); monthTable.insert(pair<string,int>("May",5)); monthTable.insert(pair<string,int>("June",6)); monthTable.insert(pair<string,int>("July",7)); monthTable.insert(pair<string,int>("August",8)); monthTable.insert(pair<string,int>("September",9)); monthTable.insert(pair<string,int>("October",10)); monthTable.insert(pair<string,int>("November",11)); monthTable.insert(pair<string,int>("December",12));
这是添加映射关系。
map<string,int>::iterator it = monthTable.find(monthString); int month = it->second;
这是查找的用法。一定要用迭代器!
代码
话不多说,学习了map以后,其他的问题就是经典的日期问题,可以看我之前的题解。代码如下:
#include <bits/stdc++.h> using namespace std; map<string,int> monthTable; string week[7] = {"Friday","Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday"}; int days [2][12]={ {31,28,31,30,31,30,31,31,30,31,30,31}, {31,29,31,30,31,30,31,31,30,31,30,31}, }; int length[2] = {365,366}; bool isLeap(int year){ if(year%400==0) return true; if(year%4==0&&year%100!=0) return true; return false; } int getNum(int year,int month,int day){ int sum = 0; for(int i=0;i<year;i++){ bool leap = isLeap(i); sum+=length[leap]; } for(int i=1;i<month;i++){ bool leap = isLeap(year); sum+=days[leap][i-1]; } sum+=day; return sum; } int main(){ monthTable.insert(pair<string,int>("January",1)); monthTable.insert(pair<string,int>("February",2)); monthTable.insert(pair<string,int>("March",3)); monthTable.insert(pair<string,int>("April",4)); monthTable.insert(pair<string,int>("May",5)); monthTable.insert(pair<string,int>("June",6)); monthTable.insert(pair<string,int>("July",7)); monthTable.insert(pair<string,int>("August",8)); monthTable.insert(pair<string,int>("September",9)); monthTable.insert(pair<string,int>("October",10)); monthTable.insert(pair<string,int>("November",11)); monthTable.insert(pair<string,int>("December",12)); int day,year; string monthString; while(cin>>day>>monthString>>year){ map<string,int>::iterator it = monthTable.find(monthString); int month = it->second; int num = getNum(year,month,day); cout<<week[num%7]<<endl; } return 0; }