# leap_year.py
def is_leap_year(year: int) -> bool:
"""
判断年份是否是闰年
闰年的2月有29天,平年的2月只有28天。
算法思想:
(1) 判断是否是世纪年。
(2) 若是世纪年,判断能否被400整除。若可以被整除,则是闰年;否则是平年。
(3) 若是平年,判断能否被4整除。若可以被整除,则是闰年;否则是平年。
:param year: 年份
:return: 闰年返回True,平年返回False
"""
if not year % 100:
# 世纪年
if year % 400:
# 不能被400整除,平年
return False
else:
# 能被400整除,闰年
return True
else:
# 普通年
if year % 4:
# 不能被4整除,平年
return False
else:
# 能被400整除,闰年
return True
if __name__ == '__main__':
result = is_leap_year(1900)
print(result)
result = is_leap_year(2000)
print(result)
result = is_leap_year(2010)
print(result)
result = is_leap_year(2016)
print(result)
"""
运行结果:
False
True
False
True
Process finished with exit code 0
"""
2_python--算法--判断年份是否是闰年
最新推荐文章于 2024-05-31 10:56:03 发布