โจทย์
Return the number of days in month of year in the Gregorian calendar. February has 29 days in a leap year: years divisible by 4, except those divisible by 100 unless also divisible by 400. A helper function is_leap(year) keeps the code tidy.
Implement days_in_month(year, month).
Input
year: The year. month: The month, 1 (January) to 12 (December).
Output
Return the number of days.
เงื่อนไข
1 ≤ year ≤ 9,999; 1 ≤ month ≤ 12
ตัวอย่าง
อินพุต:
year = 2024
month = 2
ผลลัพธ์ที่คาดหวัง:
expected = 29
อินพุต:
long long year = 2024;
long long month = 2;
ผลลัพธ์ที่คาดหวัง:
long long expected = 29;
อินพุต:
long year = 2024;
long month = 2;
ผลลัพธ์ที่คาดหวัง:
long expected = 29;
คำอธิบาย
2024 is divisible by 4 and not by 100, so it is a leap year: 29 days.
อินพุต:
year = 1900
month = 2
ผลลัพธ์ที่คาดหวัง:
expected = 28
อินพุต:
long long year = 1900;
long long month = 2;
ผลลัพธ์ที่คาดหวัง:
long long expected = 28;
อินพุต:
long year = 1900;
long month = 2;
ผลลัพธ์ที่คาดหวัง:
long expected = 28;
คำอธิบาย
1900 is divisible by 100 but not 400, so it is not a leap year: 28 days.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
เดือนส่วนใหญ่มีจำนวนวันคงที่; กุมภาพันธ์ขึ้นกับว่าเป็นปีอธิกสุรทินหรือไม่
คำใบ้ 2
ใช้ตารางจำนวนวันของแต่ละเดือน แล้วปรับกุมภาพันธ์ตามกฎปีอธิกสุรทิน
คำใบ้ 3
ระวังปีที่หาร 100 ลงตัว: ยังไม่พอ ต้องหาร 400 ลงตัวด้วย
ความซับซ้อนที่คาดหวัง
เวลา O(1), หน่วยความจำเพิ่ม O(1)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน