Algorithm
Problem Name: 1185. 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 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"
Constraints:
- The given dates are valid dates between the years
1971
and2100
.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
int[] m = {0,31,28,31,30,31,30,31,31,30,31,30,31};
String[] res = {"Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"};
public String dayOfTheWeek(int day, int month, int year) {
int days = years(year);
if(isLeap(year))
m[2] = 29;
for(int i=0; i < month; i++){
days += m[i];
}
days += day-1;
return res[days%7];
}
private int years(int y){
int count = 0;
for(int i=1971; i < y; i++){
if(isLeap(i))
count += 366;
else
count += 365;
}
return count;
}
private boolean isLeap(int y){
if(y % 4 != 0) return false;
else if(y%100 != 0) return true;
else if(y % 400 != 0> return false;
else return true;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const dayOfTheWeek = function(day, month, year) {
const weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const date = new Date(year,month-1,day).getDay();
return weekdays[date];
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
from datetime import date
class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
return date(year, month, day).strftime("%A")
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System;
namespace LeetCode
{
public class _1185_DayOfTheWeek
{
public string DayOfTheWeek(int day, int month, int year)
{
return new DateTime(year, month, day).DayOfWeek.ToString();
}
}
}
Copy The Code &
Try With Live Editor
Input
Output