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

后端 未结 10 1999
逝去的感伤
逝去的感伤 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条回答
  •  情深已故
    2021-02-05 17:25

    To speed up the calculation of the year, you could build a lookup table

    int[] YearStartDays =
    {
        0,                     // 1 AD
        365,                   // 2 AD
        365 + 365,             // 3 AD
        365 + 365 + 365,       // 4 AD
        365 + 365 + 365 + 366, // 5 AD (4 was a leap year)
        /* ... */
    };
    

    You can then do a binary search in this array, which is O(log N) instead of the O(N) of your current year finding algorithm.

提交回复
热议问题