Day of the Week

Given a date, return the corresponding day of the week for that date.

The input is given as three integers representing the daymonth 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 dayint monthint year) {
        int a[] = { 0315990120151181212243,
 273304334365 };
        String daysName[] = { "Sunday""Monday""Tuesday",
 "Wednesday""Thursday""Friday""Saturday" };

        int leapYear = 0;
        if (month < 3)
            leapYear = year - 1;
        else
            leapYear = 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 dayint monthint year)
{
    int a[13] = {0315990120151181212,
                 243273304334365};
    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 = 31month = 8year = 2019;

    cout<<dayOfTheWeek(day,month,year)<<"\n";

    return 0;
}


No comments:

Post a Comment