Day of the Week LeetCode

 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 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"

Example 3:


Input: day = 15, month = 8, year = 1993

Output: "Sunday"



import java.util.Calendar;
class Solution {
    public String dayOfTheWeek(int day, int month, int year) {
       
         String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day); // month is 0-indexed in Calendar

        int dayIndex = calendar.get(Calendar.DAY_OF_WEEK); // Sunday = 1, Saturday = 7

        return days[dayIndex - 1]; // shift to 0-based index
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence