Skip to content

Commit 82e7936

Browse files
committed
feat(day 147): add leap year calculator using standard divisibility rules
1 parent 0af9d0f commit 82e7936

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""
2+
Leap Year Calculator
3+
Given an integer year, determine whether it is a leap year.
4+
5+
A year is a leap year if it satisfies the following rules:
6+
7+
The year is evenly divisible by 4, and
8+
The year is not evenly divisible by 100, unless
9+
The year is evenly divisible by 400.
10+
"""
11+
12+
import unittest
13+
14+
class LeapYearCalculatorTest(unittest.TestCase):
15+
16+
def test1(self):
17+
self.assertEqual(is_leap_year(2024), True)
18+
19+
def test2(self):
20+
self.assertEqual(is_leap_year(2023), False)
21+
22+
def test3(self):
23+
self.assertEqual(is_leap_year(2100), False)
24+
25+
def test4(self):
26+
self.assertEqual(is_leap_year(2000), True)
27+
28+
def test5(self):
29+
self.assertEqual(is_leap_year(1999), False)
30+
31+
def test6(self):
32+
self.assertEqual(is_leap_year(2040), True)
33+
34+
def test7(self):
35+
self.assertEqual(is_leap_year(2026), False)
36+
37+
38+
39+
def is_leap_year(year):
40+
41+
return (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0))
42+
43+
"""
44+
1. Divisible by 4 -> candidate for leap year.
45+
2. Divisible by 100 -> normally not a leap year (exception case).
46+
3. Divisible by 400 -> is a leap year (special override).
47+
48+
So:
49+
-> 2000 -> leap year (divisible by 400).
50+
-> 1900 -> not a leap year (divisible by 100 but not 400).
51+
-> 2024 -> leap year (divisble by 4, not by 100).
52+
-> 2023 -> not a leap year (not divisible by 4).
53+
54+
==> Year = 2024
55+
-> 2024 % 4 == 0 -> True
56+
-> 2024 % 100 != 0 -> True
57+
-> Whole condition -> True -> Leap Year.
58+
59+
==> Year - 1900
60+
-> 1900 % 4 == 0 -> True
61+
-> 1900 % 100 != 0 -> False
62+
-> 1900 % 400 == 0 -> False
63+
-> Inner condition -> False -> Not leap year.
64+
65+
==> Year = 2000
66+
-> 2000 % 4 == 0 -> True
67+
-> 2000 % 100 != 0 -> False
68+
-> 2000 % 400 == 0 -> True
69+
-> Inner condition -> True -> Leap Year.
70+
71+
72+
-> Divisible by 4 -> candidate
73+
-> Centuries (divisible by 100) are excluded.
74+
-> Exceptioon: centuries divisible by 400 are included.
75+
"""
76+
77+
if __name__ == "__main__":
78+
print(is_leap_year(2026))
79+
unittest.main()

0 commit comments

Comments
 (0)