Is there an easy way to determine if a year is a leap year?
Is there an easy way to determine if a year is a leap year?
Here is my answer for the exercism.io problem which asks the same question. You are explicitly told to ignore any standard library functions that may implement it as part of the exercise.
class Year
attr_reader :year
def initialize(year)
@year = year
end
def leap?
if @year.modulo(4).zero?
return true unless @year.modulo(100).zero? and not @year.modulo(400).zero?
end
false
end
end
Any year that is evenly divisible by 4 is a leap year. However, there is still a small error that must be accounted for. To eliminate this error, the Gregorian calendar stipulates that a year that is evenly divisible by 100 (for example, 1900) is a leap year only if it is also evenly divisible by 400.
class Date
def self.leap?(year)
year % 4 == 0 && year % 100 != 0 || year % 400 == 0
end
end
Using the least amount possible of comparisons, you could do this:
def leap_year?(year)
# check first if year is divisible by 400
return true if year % 400 == 0
year % 4 == 0 && year % 100 != 0
end
We can do the same check using short circuit OR (||):
def leap_year?(year)
year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
end
Already a lot of answers, though here is a shorter version:
y%100 > 0 ? y%4 < 1 : y%400 < 1
If the year is not a century, then checks if it is a multiple of 4, otherwise checks if it is multiple of 400.
Here's my method:
def leap_year?(year)
Time.new(year, 12, 31).yday == 366
end
leap_year?(1999)
#=> false
leap_year?(2000)
#=> true
leap_year?(2100)
#=> false
leap_year?(2104)
#=> true