Algoritmo de Luhn
O algoritmo de Luhn é usado para validar números de cartão de crédito. O algoritmo recebe uma string como entrada e faz o seguinte para validar o número do cartão de crédito:
-
Ignore todos os espaços. Rejeite número com menos de dois dígitos.
-
Moving from right to left, double every second digit: for the number
1234, we double3and1. For the number98765, we double6and8. -
Depois de dobrar um dígito, some os dígitos. Portanto, dobrando
7torna-se14, que torna-se5. -
Some todos os dígitos, dobrados ou não.
-
O número do cartão de crédito é válido se a soma terminar em
0.
Copy the code below to https://play.rust-lang.org/ and implement the function.
Try to solve the problem the “simple” way first, using for loops and integers. Then, revisit the solution and try to implement it with iterators.
// TODO: remova isto quando você terminar sua implementação . #![allow(unused_variables, dead_code)] pub fn luhn(cc_number: &str) -> bool { unimplemented!() } #[test] fn test_non_digit_cc_number() { assert!(!luhn("foo")); } #[test] fn test_empty_cc_number() { assert!(!luhn("")); assert!(!luhn(" ")); assert!(!luhn(" ")); assert!(!luhn(" ")); } #[test] fn test_single_digit_cc_number() { assert!(!luhn("0")); } #[test] fn test_two_digit_cc_number() { assert!(luhn(" 0 0 ")); } #[test] fn test_valid_cc_number() { assert!(luhn("4263 9826 4026 9299")); assert!(luhn("4539 3195 0343 6467")); assert!(luhn("7992 7398 713")); } #[test] fn test_invalid_cc_number() { assert!(!luhn("4223 9826 4026 9299")); assert!(!luhn("4539 3195 0343 6476")); assert!(!luhn("8273 1232 7352 0569")); } #[allow(dead_code)] fn main() {}