题解 | #Zero-complexity Transposition#

Day of Week

http://www.nowcoder.com/practice/a3417270d1c0421587a60b93cdacbca0

简洁做法

/*
描述
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 2005, 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
*/

#include<iostream>
#include<string>
#include<vector>

using namespace std;


int monthDays[2][12] = {
    {31,28,31,30,31,30,31,31,30,31,30,31},        // not leap year
    {31,29,31,30,31,30,31,31,30,31,30,31}        // leap year
};


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


int main() {
    int day=0,year=0,mon=0;
    int n = 0,week_day=0;
    string month;
    vector<string>M({ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" });
    vector<string> W({ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" });
    while (cin >> day >> month >> year)
    {
        for (int i = 0; i < M.size(); ++i)
            if (M[i] == month)
                mon = i;
        n = 0;
        for (int i = 0; i < year; ++i)
            n += isLeapYear(i) ? 366 : 365;
        for (int i = 0; i < mon; ++i)
            n += monthDays[isLeapYear(year)][i];
        n += day;
        n = n + 5;
        week_day = n % 7;
        cout << W[week_day] << endl;
    }
    return 0;
}
全部评论
最后n为什么要+5呀
1 回复 分享
发布于 2021-09-26 13:33
因为他是从0年1月1日开始计算的,那一天不是星期一,把for (int i = 0; i < year; ++i)改成for (int i = 1; i < year; ++i) 就不用再+5了
点赞 回复 分享
发布于 01-18 11:18 安徽

相关推荐

双非坐过牢:非佬,可以啊10.28笔试,11.06评估11.11,11.12两面,11.19oc➕offer
点赞 评论 收藏
分享
评论
4
收藏
分享
牛客网
牛客企业服务