Topic:
Give you a date, please design an algorithm to determine which day of the week it corresponds to.
The input is three integers: day, month, and year, which represent the day, month, and year respectively.
The result you return must be one of these values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.
Example 1:
Input: day = 31, month = 8, year = 2019
Output: "Saturday"
Example 2:
Input: day = 18, month = 7, year = 1999
Output: "Sunday"
Example 3:
Input: day = 15, month = 8, year = 1993
Output: "Sunday"
prompt:
The date given must be a valid date between 1971 and 2100.
Code:
#include<iostream>
using namespace std;
int month[13][2] = {
{
0,0 }, // 0
{
31,31 }, // 1
{
28,29 }, // 2
{
31,31 }, // 3
{
30,30 }, // 4
{
31,31 }, // 5
{
30,30 }, // 6
{
31,31 }, // 7
{
31,31 }, // 8
{
30,30 }, // 9
{
31,31 }, // 10
{
30,30 }, // 11
{
31,31 } // 12
};
bool isyeap(int year)
{
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return true;
else
return false;
}
int main()
{
int t2, t1 = 19710101;
cin >> t2;
int y1, m1, d1;
int y2, m2, d2;
y1 = t1 / 10000, m1 = t1 % 10000 / 100, d1 = t1 % 100;
y2 = t2 / 10000, m2 = t2 % 10000 / 100, d2 = t2 % 100;
int counter = 1;
while (y1 != y2 || m1 != m2 || d1 != d2)
{
counter++;
d1++;
if (d1 == month[m1][isyeap(y1) + 1])
{
d1 = 1;
m1++;
}
if (m1 == 13)
{
m1 = 1;
y1++;
}
}
cout << counter << endl;
int num;
num = counter % 7;
switch (num-1)
{
case 0: cout << "Friday" << endl; break;
case 1: cout << "Saturday" << endl; break;
case 2: cout << "Sunday" << endl; break;
case 3: cout << "Monday" << endl; break;
case 4: cout << "Tuesday" << endl; break;
case 5: cout << "Wednesday" << endl; break;
case 6: cout << "Thursday" << endl; break;
}
system("pause");
return 0;
}
Summary after the code: This
question is a typical question among the date questions. The essence is to find the difference between two dates, which is worth doing.