How to Compute the Number of Days in a Month?
- 时间:2020-09-21 09:15:21
- 分类:网络文摘
- 阅读:107 次
Given a year Y and a month M, return how many days there are in that month.
Example 1:
Input: Y = 1992, M = 7
Output: 31Example 2:
Input: Y = 2000, M = 2
Output: 29Example 3:
Input: Y = 1900, M = 2
Output: 28Note:
1583 <= Y <= 2100
1 <= M <= 12
The special case is the February: 29 days if it is a leap year and 28 days otherwise. All other months either have 30 or 31 days. Therefore, using a simple switch-statement in C/C++/Java should do it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Solution { public: int numberOfDays(int Y, int M) { if (M == 2) { if (isLeap(Y)) return 29; return 28; } switch (M) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; } return 30; } private: bool isLeap(int Y) { if (Y % 400 == 0) { return true; } else if ( Y % 100 == 0) { return false; } else if (Y % 4 == 0) { return true; } else { return false; } } }; |
class Solution {
public:
int numberOfDays(int Y, int M) {
if (M == 2) {
if (isLeap(Y)) return 29;
return 28;
}
switch (M) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
}
return 30;
}
private:
bool isLeap(int Y) {
if (Y % 400 == 0) {
return true;
} else if ( Y % 100 == 0) {
return false;
} else if (Y % 4 == 0) {
return true;
} else {
return false;
}
}
};The above C++ program uses the isLeap method to test for leap year. And both the time and space complexity is O(1) constant.
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:CCTV5在线直播-中央五台直播在线观看「高清」 CCTV5+在线直播-CCTV5+体育赛事在线直播「高清」 CCTV6在线直播-中央六台直播在线观看「高清」 CCTV7在线直播-中央七台直播在线观看「高清」 CCTV8在线直播-中央八台直播在线观看「高清」 CCTV9在线直播-中央九台直播在线观看「高清」 CCTV10在线直播-中央十台直播在线观看「高清」 CCTV11在线直播-中央十一台直播在线观看「高清」 CCTV12在线直播-中央十二台直播在线观看「高清」 CCTV13在线直播-中央十三台直播在线观看「高清」
- 评论列表
-
- 添加评论