返回介绍

solution / 1100-1199 / 1118.Number of Days in a Month / README_EN

发布于 2024-06-17 01:03:23 字数 3261 浏览 0 评论 0 收藏 0

1118. Number of Days in a Month

中文文档

Description

Given a year year and a month month, return _the number of days of that month_.

 

Example 1:

Input: year = 1992, month = 7
Output: 31

Example 2:

Input: year = 2000, month = 2
Output: 29

Example 3:

Input: year = 1900, month = 2
Output: 28

 

Constraints:

  • 1583 <= year <= 2100
  • 1 <= month <= 12

Solutions

Solution 1: Determine Leap Year

We can first determine whether the given year is a leap year. If the year can be divided by $4$ but not by $100$, or can be divided by $400$, then this year is a leap year.

February has $29$ days in a leap year and $28$ days in a common year.

We can use an array $days$ to store the number of days in each month of the current year, where $days[0]=0$, $days[i]$ represents the number of days in the $i$th month of the current year. Then the answer is $days[month]$.

The time complexity is $O(1)$, and the space complexity is $O(1)$.

class Solution:
  def numberOfDays(self, year: int, month: int) -> int:
    leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
    days = [0, 31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    return days[month]
class Solution {
  public int numberOfDays(int year, int month) {
    boolean leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    int[] days = new int[] {0, 31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    return days[month];
  }
}
class Solution {
public:
  int numberOfDays(int year, int month) {
    bool leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    vector<int> days = {0, 31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    return days[month];
  }
};
func numberOfDays(year int, month int) int {
  leap := (year%4 == 0 && year%100 != 0) || (year%400 == 0)
  x := 28
  if leap {
    x = 29
  }
  days := []int{0, 31, x, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  return days[month]
}
function numberOfDays(year: number, month: number): number {
  const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  const days = [0, 31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  return days[month];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文