Determine the number of days per month

I am getting year , month and day as input, and I am trying to efficiently check input. The range of the year is [0-99] (0.4.8 .. are considered leap years), the range of the month [1-12] and the day range [1-31].

The direct way to check the day is as follows:

if( (Day<1u) || (Day>31u) ){ /*error*/ } else if ( (Month==4u) || (Month==6u) || (Month==9u) || (Month==11u) && (Day>30u) ){ /*error*/ } else if ( (Month==2u) && (Year % 4u == 0u) && (Day > 29u) ){ /*error*/ } else if ( (Month==2u) && (Year % 4u != 0u) && (Day > 28u) ){ /*error*/ } else { /*valid*/ } 

But it has a high complexity.

The lookup table looks like the best choice. And now the question is:

Is there a more efficient way to create a table for this case other than the following?

 const int testTable[4][12] = { {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; if( testTable[ Year % 4 ][ Month - 1 ] >= Day){ /*valid*/ } else{ /*error*/ } 

Is there any other rule that I don't see?

+6
source share
1 answer

You need one dimension for leap years and another for off-season years:

 int isleap(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } int mthdays(int month, int year) { static const int days[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; int leap = isleap(year); return days[leap][month]; } 

Range of the year [0-99] (0.4.8 .. are considered leap years)

Then your isleap() function should be:

 int isleap(int year) { return (year % 4 == 0); } 

range of months [1-12]

Using:

 {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} 

instead

 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} 

you can avoid [ Month - 1 ]

+6
source

All Articles