Efficient algorithm for converting number of days to years (including leap years)

后端 未结 10 1982
逝去的感伤
逝去的感伤 2021-02-05 17:04

The problem

I am writing a class for holding dates in c++, and I found the following problem:

I have a number of days N since a reference date (in

10条回答
  •  梦毁少年i
    2021-02-05 17:33

    Let me simplify the question, I won't consider exceptions for explanation. Every 4 years, a leap occur, if you have 365*5 days, there must be a leap-year (unless if the exception 2 is applied). You could just use division for having the number of leap-years (if ignoring the exceptions).

    Then you can easily use division and remainder for having the non-leap years/months/days.

    Use the same basic intuition for resolving the Exception 1 (if the number of years is a multiple of 100, then also check the Exception 2)

    1. Years which are divisible by 4 are leap
    2. Exception to rule 1: years that are divisible with 100 are not leap
    3. Exception to rule 2: years that are divisible with 400 are leap

提交回复
热议问题