# LeetCode - 1185 - 一周中的第几天（day-of-the-week）

## 二 前言

• 难度：简单

• 涉及知识：数组

• 题目地址：https://leetcode-cn.com/problems/day-of-the-week/

• 题目内容

给你一个日期，请你设计一个算法来判断它是对应一周中的哪一天。

{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
}。



## 三 解题及测试

• LeetCode 给定函数体

/**
* @param {number} day
* @param {number} month
* @param {number} year
* @return {string}
*/
var dayOfTheWeek = function(day, month, year) {

};


index.js

/**
* @name 一周中的第几天
* @param {number} day
* @param {number} month
* @param {number} year
* @return {string}
*/
const dayOfTheWeek = (day, month, year) => {
if (month === 1 || month === 2) {
month += 12;
year -= 1;
}
const result = (day + 1 + 2 * month + Math.floor(3 * (month + 1) / 5) + year + Math.floor(year / 4) - Math.floor(year / 100) + Math.floor(year / 400)) % 7;
return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][result];
};

console.log(dayOfTheWeek(31, 1, 2020)); // 'Firday'
console.log(dayOfTheWeek(18, 7, 1999)); // 'Sunday'


node index.js 返回：

'Firday'
'Sunday'


## 四 LeetCode Submit

Accepted
* 39/39 cases passed (64 ms)
* Your runtime beats 59.11 % of javascript submissions
* Your memory usage beats 76.88 % of javascript submissions (33.8 MB)


## 五 解题思路

const dayOfTheWeek = (day, month, year) => {
if (month === 1 || month === 2) {
month += 12;
year -= 1;
}
const result = (day + 1 + 2 * month + Math.floor(3 * (month + 1) / 5) + year + Math.floor(year / 4) - Math.floor(year / 100) + Math.floor(year / 400)) % 7;
return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][result];
};


Submit 提交：

Accepted
* 39/39 cases passed (64 ms)
* Your runtime beats 59.11 % of javascript submissions
* Your memory usage beats 76.88 % of javascript submissions (33.8 MB)


## 六 进一步思考

const dayOfTheWeek = (day, month, year) => {
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let x = ${year}/${month}/\${day};
let date = new Date(Date.parse(x));
return days[date.getDay()];
};


Submit 提交：

Accepted
* 39/39 cases passed (52 ms)
* Your runtime beats 95.57 % of javascript submissions
* Your memory usage beats 35.63 % of javascript submissions (34.1 MB)


jsliang 会每天更新一道 LeetCode 题解，从而帮助小伙伴们夯实原生 JS 基础，了解与学习算法与数据结构。

jsliang 的文档库 由 梁峻荣 采用 知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议进行许可。

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客