C程序 检查闰年
如果一年是400的倍数,以及一年是4的倍数但不是100的倍数,那么这一年就是一个闰年。
比如说。
- 2000年是闰年
- 2022年不是闰年
- 2019年不是闰年
以下是伪代码。
if year is divisible by 400 then is_leap_year
else if year is divisible by 100 then not_leap_year
else if year is divisible by 4 then is_leap_year
else not_leap_year
// C program to check if a given
// year is leap year or not
#include <stdio.h>
#include <stdbool.h>
bool checkYear(int year)
{
// If a year is multiple of 400,
// then it is a leap year
if (year % 400 == 0)
return true;
// Else If a year is multiple of 100,
// then it is not a leap year
if (year % 100 == 0)
return false;
// Else If a year is multiple of 4,
// then it is a leap year
if (year % 4 == 0)
return true;
return false;
}
// Driver code
int main()
{
int year = 2000;
checkYear(year)? printf("Leap Year"):
printf("Not a Leap Year");
return 0;
}
输出
Leap Year
- Time Complexity: O(1)
- Auxiliary Space: O(1)
如何在一行中写出上述代码?
// One line C program to check if a
// given year is leap year or not
#include <stdio.h>
#include <stdbool.h>
bool checkYear(int year)
{
// Return true if year is a multiple
// of 4 and not multiple of 100.
// OR year is multiple of 400.
return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
}
// Driver code
int main()
{
int year = 2000;
checkYear(year)? printf("Leap Year"):printf("Not a Leap Year");
return 0;
}
输出
Leap Year
- Time Complexity: O(1)
- Auxiliary Space: O(1)