雨滴声-Raindrops

1. Readme

雨滴-Raindrops

把一个数字转换成一个字符串,它的内容取决于,数字的因素.

  • 如果数字有 3 作为一个因素,输出”Pling”.
  • 如果数字有 5 作为一个因素,输出”Plang’”.
  • 如果数字有 7 作为一个因素,输出”Plong”.
  • 如果数字没有 3, 5,或 7 作为一个因素, 直接给数字。

实例

  • 28 的因素是 1, 2, 4, 7,14, 28.
    • 雨滴说,这将是一个简单的”Plong”.
  • 30 的因素是 1, 2,3,5,6, 10, 15,30.
    • 雨滴说,这将是一个”PlingPlang”.
  • 34 有四个因素:1, 2, 17,34.
    • 雨滴说,这将是”34”.

Source

A variation on a famous interview question intended to weed out potential candidates. http://jumpstartlab.com

2. 开始你的表演

pub fn raindrops(n: u32) -> String {
   unimplemented!("what sound does Raindrop #{} make?", n)
}

3. 测试代码查看


# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_1() {
   assert_eq!("1", raindrops(1));
}

#[test]
//#[ignore]
fn test_3() {
   assert_eq!("Pling", raindrops(3));
}

#[test]
//#[ignore]
fn test_5() {
   assert_eq!("Plang", raindrops(5));
}

#[test]
//#[ignore]
fn test_7() {
   assert_eq!("Plong", raindrops(7));
}

#[test]
//#[ignore]
fn test_6() {
   assert_eq!("Pling", raindrops(6));
}

#[test]
//#[ignore]
fn test_8() {
   assert_eq!("8", raindrops(8));
}

#[test]
//#[ignore]
fn test_9() {
   assert_eq!("Pling", raindrops(9));
}

#[test]
//#[ignore]
fn test_10() {
   assert_eq!("Plang", raindrops(10));
}

#[test]
//#[ignore]
fn test_14() {
   assert_eq!("Plong", raindrops(14));
}

#[test]
//#[ignore]
fn test_15() {
   assert_eq!("PlingPlang", raindrops(15));
}

#[test]
//#[ignore]
fn test_21() {
   assert_eq!("PlingPlong", raindrops(21));
}

#[test]
//#[ignore]
fn test_25() {
   assert_eq!("Plang", raindrops(25));
}

#[test]
//#[ignore]
fn test_27() {
   assert_eq!("Pling", raindrops(27));
}

#[test]
//#[ignore]
fn test_35() {
   assert_eq!("PlangPlong", raindrops(35));
}

#[test]
//#[ignore]
fn test_49() {
   assert_eq!("Plong", raindrops(49));
}

#[test]
//#[ignore]
fn test_52() {
   assert_eq!("52", raindrops(52));
}

#[test]
//#[ignore]
fn test_105() {
   assert_eq!("PlingPlangPlong", raindrops(105));
}

#[test]
//#[ignore]
fn test_3125() {
   assert_eq!("Plang", raindrops(3125));
}

#[test]
//#[ignore]
fn test_12121() {
   assert_eq!("12121", raindrops(12121));
}

#}

4. 答案


# #![allow(unused_variables)]
#fn main() {
pub fn raindrops(n: u32) -> String {
   let is_pling = |n| n % 3 == 0;
   let is_plang = |n| n % 5 == 0;
   let is_plong = |n| n % 7 == 0;
   let mut drops = String::new();
   if is_pling(n) {
       drops.push_str("Pling");
   }
   if is_plang(n) {
       drops.push_str("Plang");
   }
   if is_plong(n) {
       drops.push_str("Plong");
   }
   if drops.is_empty() {
       let s = format!("{}", n);
       drops.push_str(&s);
   }
   drops
}

#}



填充/相关