Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the day
, month
and a year respectively.
Return the answer as one of the following 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"
Approach
Java
public class DayOfWeek {public static void main(String[] args) {int day = 31, month = 8, year = 2019;System.out.println(dayOfTheWeek(day, month, year));}static String dayOfTheWeek(int day, int month, int year) {int a[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243,273, 304, 334, 365 };String daysName[] = { "Sunday", "Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday" };int leapYear = 0;if (month < 3)leapYear = year - 1;elseleapYear = year;int leapYearCount = leapYear / 4 - 492;int totaldays = leapYearCount + (year - 1971) *365 + a[month - 1] + day;if (year == 2100 && month > 2)totaldays--;totaldays = totaldays % 7;return daysName[(4 + totaldays) % 7];}}
C++
#include <bits/stdc++.h>using namespace std;string dayOfTheWeek(int day, int month, int year){int a[13] = {0, 31, 59, 90, 120, 151, 181, 212,243, 273, 304, 334, 365};string daysName[] = {"Sunday", "Monday", "Tuesday","Wednesday","Thursday", "Friday", "Saturday"};int leapYear = year - (month < 3);int leapYearCount = leapYear / 4 - 492;int totaldays = leapYearCount + (year - 1971) * 365 +a[month - 1] + day;if (year == 2100 && month > 2)totaldays--;totaldays = totaldays % 7;return daysName[(4 + totaldays) % 7];}int main(){int day = 31, month = 8, year = 2019;cout<<dayOfTheWeek(day,month,year)<<"\n";return 0;}
No comments:
Post a Comment