Luhn Algorithm
The Luhn algorithm is used to validate credit card numbers. The algorithm takes a string as input and does the following to validate the credit card number:
- Ignore all spaces. Reject number with less than two digits.
- Moving from right to left, double every second digit: for the number
1234, we double3and1. - After doubling a digit, sum the digits. So doubling
7becomes14which becomes5. - Sum all the undoubled and doubled digits.
- The credit card number is valid if the sum ends with
0.
Copy the following code to <https://play.rust-lang.org/> and implement the function:
1. // TODO: remove this when you're done with your implementation.
2. #![allow(unused_variables, dead_code)]
4. pub fn luhn(cc_number: &str) -> bool {
5. unimplemented!()
6. }
8. #[test]
9. fn test_non_digit_cc_number() {
10. assert!(!luhn("foo"));
11. }
13. #[test]
14. fn test_empty_cc_number() {
15. assert!(!luhn(""));
16. assert!(!luhn(" "));
17. assert!(!luhn(" "));
18. assert!(!luhn(" "));
19. }
21. #[test]
22. fn test_single_digit_cc_number() {
23. assert!(!luhn("0"));
24. }
26. #[test]
27. fn test_two_digit_cc_number() {
28. assert!(luhn(" 0 0 "));
29. }
31. #[test]
32. fn test_valid_cc_number() {
33. assert!(luhn("4263 9826 4026 9299"));
34. assert!(luhn("4539 3195 0343 6467"));
35. assert!(luhn("7992 7398 713"));
36. }
38. #[test]
39. fn test_invalid_cc_number() {
40. assert!(!luhn("4223 9826 4026 9299"));
41. assert!(!luhn("4539 3195 0343 6476"));
42. assert!(!luhn("8273 1232 7352 0569"));
43. }
45. #[allow(dead_code)]
46. fn main() {}
