Skip to content

Commit cc31fbd

Browse files
authored
Create 1118-number-of-days-in-a-month.js
1 parent 69ba683 commit cc31fbd

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

1118-number-of-days-in-a-month.js

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
3+
Given a year Y and a month M, return how many days there are in that month.
4+
5+
Example 1:
6+
7+
Input: Y = 1992, M = 7
8+
Output: 31
9+
Example 2:
10+
11+
Input: Y = 2000, M = 2
12+
Output: 29
13+
Example 3:
14+
15+
Input: Y = 1900, M = 2
16+
Output: 28
17+
18+
Note:
19+
20+
1583 <= Y <= 2100
21+
1 <= M <= 12
22+
23+
*/
24+
25+
/**
26+
* @param {number} Y
27+
* @param {number} M
28+
* @return {number}
29+
*/
30+
function numberOfDays(Y, M) {
31+
switch (M) {
32+
case 2:
33+
return Y % 400 === 0 || (Y % 4 === 0 && Y % 100 !== 0) ? 29 : 28;
34+
case 4:
35+
case 6:
36+
case 9:
37+
case 11:
38+
return 30;
39+
default:
40+
return 31;
41+
}
42+
}
43+
44+
// another
45+
46+
/**
47+
* @param {number} Y
48+
* @param {number} M
49+
* @return {number}
50+
*/
51+
const numberOfDays = function(Y, M) {
52+
const d = new Date(Y, M - 1)
53+
let num = 0
54+
while(d.getMonth() === M - 1) {
55+
num++
56+
const n = d.getDate()
57+
d.setDate(n + 1)
58+
}
59+
return num
60+
};

0 commit comments

Comments
 (0)