闰年-Leap

1. Readme

Leap

给出年份,报告是不是闰年.

这里的棘手问题是公历中,闰年计算:

我想也很清楚了,就不译了

on every year that is evenly divisible by 4
  except every year that is evenly divisible by 100
    unless the year is also evenly divisible by 400

例如,1997不是闰年,而是1996是,1900不是闰年,而2000是。

如果在您的语言标准库中,提供了执行此实现的方法, 请假装它不存在,并自己实现它.

笔记

虽然我们的采用一些非常简单的规则,但还有更多的东西要学!

为了一个令人愉快的,为什么有闰年现象的解释,请观看这个YouTube视频.

译: 我给个李永乐老师的视频:>youtube :> bilibili

Source

JavaRanch Cattle Drive, exercise 3 http://www.javaranch.com/leap.jsp

2. 开始你的表演

pub fn is_leap_year(year: i32) -> bool {
   unimplemented!("true if {} is a leap year", year)
}

3. 测试代码查看


# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_vanilla_leap_year() {
   assert_eq!(is_leap_year(1996), true);
}

#[test]
//#[ignore]
fn test_any_old_year() {
   assert_eq!(is_leap_year(1997), false);
}

#[test]
//#[ignore]
fn test_century() {
   assert_eq!(is_leap_year(1700), false);
   assert_eq!(is_leap_year(1800), false);
   assert_eq!(is_leap_year(1900), false);
}

#[test]
//#[ignore]
fn test_exceptional_centuries() {
   assert_eq!(is_leap_year(1600), true);
   assert_eq!(is_leap_year(2000), true);
   assert_eq!(is_leap_year(2400), true);
}

#[test]
//#[ignore]
fn test_years_1600_to_1699() {
   let incorrect_years = (1600..1700)
       .filter(|&year| is_leap_year(year) != (year % 4 == 0))
       .collect::<Vec<_>>();

   if !incorrect_years.is_empty() {
       panic!("incorrect result for years: {:?}", incorrect_years);
   }
}

#}

4. 答案


# #![allow(unused_variables)]
#fn main() {
pub fn is_leap_year(year: i32) -> bool {
   let has_factor = |n| year % n == 0;
   has_factor(4) && (!has_factor(100) || has_factor(400))
}

#}



填充/相关