Trung bình 0 đã giải Tỷ lệ chấp nhận 0%

Counting Sundays

Count the months in a range of years that begin on a Sunday.

Bạn sẽ học được gì

  • Apply the Gregorian leap year rule
  • Track the weekday as days pass
  • Count events over a range of months

Đề bài

Xem bản dịch

A club meets on the first day of every month, and those meetings that land on a Sunday get a brunch. Count the months from January of start_year to December of end_year whose first day is a Sunday, using the Gregorian calendar. As a fixed point: 1 January 2023 was a Sunday. Remember the leap year rule: divisible by 4, except century years, which must be divisible by 400.

Implement counting_sundays(start_year, end_year).

Input

start_year: The first year, counted from January.

end_year: The last year, counted through December.

Output

Return the number of months in that range whose first day is a Sunday.

Ràng buộc

1600 ≤ start_year ≤ end_year ≤ 2400

Ví dụ

Ví dụ 1
Đầu vào:
start_year = 2023
end_year = 2023

Kết quả mong đợi:
expected = 2
Đầu vào:
long long start_year = 2023;
long long end_year = 2023;

Kết quả mong đợi:
long long expected = 2;
Đầu vào:
long start_year = 2023;
long end_year = 2023;

Kết quả mong đợi:
long expected = 2;

Giải thích

In 2023 only January and October began on a Sunday, so the answer is 2.

Ví dụ 2
Đầu vào:
start_year = 2024
end_year = 2025

Kết quả mong đợi:
expected = 3
Đầu vào:
long long start_year = 2024;
long long end_year = 2025;

Kết quả mong đợi:
long long expected = 3;
Đầu vào:
long start_year = 2024;
long end_year = 2025;

Kết quả mong đợi:
long expected = 3;

Giải thích

2024 had September and December, 2025 had June: 3 months.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

Find the weekday of January 1 of the start year from a known date, or use a weekday formula.

Gợi ý 2

Moving to the next month shifts the weekday by that month's length mod 7.

Gợi ý 3

February has 29 days in leap years: divisible by 4, but century years only when divisible by 400.

Độ phức tạp mong đợi

O(years) time, O(1) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.