L2 - 日曆

題解ios

  這一題,乍一看,很簡單,初始時我也這麼覺得,模擬了一下結果TLE了,後來再把天數減到小於一年時,又Error了。spa

       後來從新作了一下,估計是,閏年的狀態使用了上一次的結果致使,其實直接對第二月賦值便可,真是想多了啊/(ㄒoㄒ)/~~。3d

#include <iostream>
using namespace std;

int month[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
string week[7] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
int r;
int y = 2020, m = 1, d = 1, w = 5; 

int isleap(int x)
{
    return x % 4 == 0 && x % 100 != 0 || x % 400 == 0;
}

void caltime(int r)
{
    while (r--) {
        if (d == month[m]) {
            if (m == 12) {
                ++y;
                if (isleap(y)) month[2] = 29;
                else month[2] = 28;
                m = 1;
            }
            else {
                ++m;
            }
            d = 1;
        }
        else {
            ++d;
        }
        ++w;
        if (w == 7) w = 0;
    }
    cout << y << '-';
    if (m < 10) cout << 0 << m;
    else cout << m;
    cout << '-';
    if (d < 10) cout << 0 << d;
    else cout << d;
    cout << " ";
    cout << week[w] << endl;
}

int main()
{
    cin >> r;
    while (r != -1) {
        y = 2000, m = 1, d = 1, w = 5;
        int ys = 366; // 初始 2000 
        while (ys <= r) {
            w = (w + ys) % 7;
            r -= ys;
            ++y;
            if (isleap(y)) ys = 366;
            else ys = 365;
        }
        if (isleap(y)) month[2] = 29;
        else month[2] = 28;
        caltime(r);
        cin >> r;
    }
    return 0;
}
相關文章
相關標籤/搜索