Palindrome Products

1. Readme

回文乘数

在给定范围内,检测回文乘数.

回文数是指当数字倒过来时,保持不变的数。例如,121是回文数,但112不是。

给定一系列数字,找出最大和最小回文,这是该范围内数字的乘积.

您的解决方案应该返回最大和最小回文,以及范围内的每个因素。如果最大或最小回文在范围内,有多于一对的因素,则返回所有的对.

例 1

给定范围[1, 9](包含 1,9)

并给出在这个范围内的列表中,所有可能的乘数:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 15, 21, 24, 27, 20, 28, 32, 36, 25, 30, 35, 40, 45, 42, 48, 54, 49, 56, 63, 64, 72, 81]

回文乘数都是单数数字(在这种情况下):[1, 2, 3, 4, 5, 6, 7, 8, 9]

最小回文乘数是1。 其因素是(1, 1)。 最大回文乘数是9。 其因素是(1, 9)(3, 3)

例 2

给定范围[10, 99](包含)

最小回文乘数是121。 其因素是(11, 11)。 最大回文乘数是9009。 其因素是(91, 99)

资源

欧拉项目的问题 4http://projecteuler.net/problem=4

2. 开始你的表演

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

3. 测试代码查看

#[test] fn single_digits() { let palindromes = get_palindrome_products(1, 9); assert_eq!(min(&palindromes), Some(1)); assert_eq!(max(&palindromes), Some(9)); } #[test] //#[ignore] fn double_digits() { let palindromes = get_palindrome_products(10, 99); assert_eq!(min(&palindromes), Some(121)); assert_eq!(max(&palindromes), Some(9009)); } #[test] //#[ignore] fn triple_digits() { let palindromes = get_palindrome_products(100, 999); assert_eq!(min(&palindromes), Some(10201)); assert_eq!(max(&palindromes), Some(906609)); } #[test] //#[ignore] fn four_digits() { let palindromes = get_palindrome_products(1000, 9999); assert_eq!(min(&palindromes), Some(1002001)); assert_eq!(max(&palindromes), Some(99000099)); } #[test] //#[ignore] fn empty_result_for_smallest_palindrome() { assert_eq!(min(&get_palindrome_products(1002, 1003)), None); } #[test] //#[ignore] fn empty_result_for_largest_palindrome() { assert_eq!(max(&get_palindrome_products(15, 15)), None); } #[test] //#[ignore] fn error_smallest_palindrome_when_min_gt_max() { assert_eq!(min(&get_palindrome_products(1000, 1)), None); } #[test] //#[ignore] fn error_largest_palindrome_when_min_st_max() { assert_eq!(max(&get_palindrome_products(2, 1)), None); }

4. 答案

pub type Palindrome = u64; pub fn get_palindrome_products(min: u64, max: u64) -> Vec<Palindrome> { let mut palindromes: Vec<u64> = Vec::new(); for i in min..max + 1 { for j in min..max + 1 { if is_palindrome(i * j) { palindromes.push(i * j); } } } palindromes } pub fn min(palindromes: &[Palindrome]) -> Option<Palindrome> { palindromes.iter().min().map(|n| n.clone()) } pub fn max(palindromes: &[Palindrome]) -> Option<Palindrome> { palindromes.iter().max().map(|n| n.clone()) } fn is_palindrome(n: u64) -> bool { let s = n.to_string().into_bytes(); s.iter().zip(s.iter().rev()).all(|(c1, c2)| c1 == c2) }



填充/相关