Introduction
This blog will discuss the approach to check whether the given number is a leap year or not.
Before understanding the approach and code, let's first discuss leap year.
All years which are perfectly divisible by 4 are leap years except for century years (years ending with 00), which are leap years only if they are perfectly divisible by 400.
Sample Examples
Example 1:
Input: 2006
Output: 2006 is not a leap number.
Explanation: 2006 is not divisible by 4, hence it is not a leap year.
Example 2:
Input: 2000
Output: 2000 is a leap year
Explanation: 2000 is divisible by 4 as well as 400, hence it is a leap year.
Solution Approach
The solution to this problem is very trivial, we will check if the number is divisible by 4, and not 100, or if the number is divisible by 400, then it is a leap year.
Implementation in C++
// c++ program to check whether the given number is leap year or not
#include<bits/stdc++.h>
using namespace std;
bool isLeapYear(int n){
// if the condition for leap year is satisfied, return true
if((n%4==0) && (n%100!=0 || n%400==0))
return true;
// return false otherwise
return false;
}
int main(){
int n = 1604;
if(isLeapYear(n))
cout << n << " is a leap year" << endl;
else
cout << n << " is not a leap year" << endl;
}
Output:
1604 is a leap year
Try and compile with online c++ compiler.
Complexity Analysis
Time Complexity: O(1)
Explanation: only constant time operations are performed.
Space Complexity: O(1)
Explanation: We are not using any explicit space, so O(1) time complexity.
Also read - Decimal to Binary c++