Adding a number of days to a calendar date
Question
Design an algorithm that takes a date and an integer and returns the date days later, getting leap years right including the century exceptions.
Short answer
Convert to a serial day count, add , convert back. A year is leap if divisible by , except century years, which are leap only if divisible by (so 1900 is not, 2000 is). Map the date to days since a fixed epoch (whole years, then months via a cumulative table, then days), add , and invert by stepping or with a closed form; this avoids error-prone month-by-month loops and handles negative too.
Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q5.5, p.158; question and answer rewritten by SelfMadeQuant.com.
See the hint and the full worked solution in the question bank (free account).
Open the worked solution