Which years are leap years?
To be a leap year, the year number must be divisible by four – except for end-of-century years, which must be divisible by 400. This means that the year 2000 was a leap year, although 1900 was not. 2020, 2024 and 2028 are all leap years.
using System; public class LeapYears { public static bool IsLeapYear(int year) { // End of a century must be divisible by 400 if(year.ToString().EndsWith("00") && year % 400 == 0) return true; // Not the end of a century must be divisible by 4 else if(!year.ToString().EndsWith("00") && year % 4 == 0) return true; else return false; } }
- using System;
- public class LeapYears
- {
// Works but hurtspublic static bool IsLeapYear(int y) => (y % 400 == 0) ? true : (y % 100 == 0 && y % 400 != 0) ? false : (y % 4 == 0 && y % 100 != 0) ? true : false;- public static bool IsLeapYear(int year)
- {
- // End of a century must be divisible by 400
- if(year.ToString().EndsWith("00") && year % 400 == 0)
- return true;
- // Not the end of a century must be divisible by 4
- else if(!year.ToString().EndsWith("00") && year % 4 == 0)
- return true;
- else
- return false;
- }
- }
namespace Solution { using NUnit.Framework; using System; [TestFixture] public class LeapTests { [Test] public void Test1() { Assert.AreEqual(true, LeapYears.IsLeapYear(2000)); } [Test] public void Test2() { Assert.AreEqual(true, LeapYears.IsLeapYear(2004)); } [Test] public void Test3() { Assert.AreEqual(true, LeapYears.IsLeapYear(2008)); } [Test] public void Test4() { Assert.AreEqual(false, LeapYears.IsLeapYear(1913)); } [Test] public void Test5() { Assert.AreEqual(true, LeapYears.IsLeapYear(1848)); } [Test] public void Test6() { Assert.AreEqual(false, LeapYears.IsLeapYear(2397)); } [Test] public void Test7() { Assert.AreEqual(false, LeapYears.IsLeapYear(1900)); } } }
- namespace Solution {
- using NUnit.Framework;
- using System;
- [TestFixture]
- public class LeapTests
- {
- [Test]
- public void Test1()
- {
- Assert.AreEqual(true, LeapYears.IsLeapYear(2000));
- }
- [Test]
- public void Test2()
- {
- Assert.AreEqual(true, LeapYears.IsLeapYear(2004));
- }
- [Test]
- public void Test3()
- {
- Assert.AreEqual(true, LeapYears.IsLeapYear(2008));
- }
- [Test]
- public void Test4()
- {
- Assert.AreEqual(false, LeapYears.IsLeapYear(1913));
- }
- [Test]
- public void Test5()
- {
- Assert.AreEqual(true, LeapYears.IsLeapYear(1848));
- }
- [Test]
- public void Test6()
- {
- Assert.AreEqual(false, LeapYears.IsLeapYear(2397));
- }
- [Test]
- public void Test7()
- {
- Assert.AreEqual(false, LeapYears.IsLeapYear(1900));
- }
- }
- }