A Leap year occurs mostly every 4 years, but every 100 years, we skip a leap year, unless it is divisible by 400.
Leap Year Algorithm
if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)
How to Test Leap Year in C++?
bool isLeap(int Y) {
if (Y % 400 == 0) {
return true;
} else if ( Y % 100 == 0) {
return false;
} else if (Y % 4 == 0) {
return true;
} else {
return false;
}
}
Or shorter:
bool isLeap(int Y) {
return (Y % 400 == 0) || ((Y % 100 != 0) && (Y % 4 == 0));
}
How to Test Leap Year in C?
int isLeap(int Y) {
if (Y % 400 == 0) {
return true;
} else if ( Y % 100 == 0) {
return false;
} else if (Y % 4 == 0) {
return true;
} else {
return false;
}
}
Or shorter:
int isLeap(int Y) {
return (Y % 400 == 0) || ((Y % 100 != 0) && (Y % 4 == 0));
}
How to Test Leap Year in Java?
boolean isLeap(int Y) {
if (Y % 400 == 0) {
return true;
} else if ( Y % 100 == 0) {
return false;
} else if (Y % 4 == 0) {
return true;
} else {
return false;
}
}
Or shorter:
boolean isLeap(int Y) {
return (Y % 400 == 0) || ((Y % 100 != 0) && (Y % 4 == 0));
}
How to Test Leap Year in Javascript?
var isLeap = function(Y) {
if (Y % 400 == 0) {
return true;
} else if ( Y % 100 == 0) {
return false;
} else if (Y % 4 == 0) {
return true;
} else {
return false;
}
}
Or shorter:
var isLeap = function(Y) {
return (Y % 400 == 0) || ((Y % 100 != 0) && (Y % 4 == 0));
}
How to Test Leap Year in Python/Python3?
def isLeap(Y):
if Y % 400 == 0:
return True
elif Y % 100 == 0:
return False
elif Y % 4 == 0:
return True
else:
return False
or shorter:
def isLeap(Y):
return (Y % 400 == 0) or ((Y % 100 != 0) and (Y % 4 == 0))
All Leap Year Algorithms run at O(1) time and O(1) constant space.
–EOF (The Ultimate Computing & Technology Blog) —
361 wordsLast Post: Python Algorithm to Determine an Armstrong Number
Next Post: How to Compute the Number of Days in a Month?