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 double 3 and 1.

  • After doubling a digit, sum the digits. So doubling 7 becomes 14 which becomes 5.

  • 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)]
  3. pub fn luhn(cc_number: &str) -> bool {
  4. unimplemented!()
  5. }
  6. #[test]
  7. fn test_non_digit_cc_number() {
  8. assert!(!luhn("foo"));
  9. }
  10. #[test]
  11. fn test_empty_cc_number() {
  12. assert!(!luhn(""));
  13. assert!(!luhn(" "));
  14. assert!(!luhn(" "));
  15. assert!(!luhn(" "));
  16. }
  17. #[test]
  18. fn test_single_digit_cc_number() {
  19. assert!(!luhn("0"));
  20. }
  21. #[test]
  22. fn test_two_digit_cc_number() {
  23. assert!(luhn(" 0 0 "));
  24. }
  25. #[test]
  26. fn test_valid_cc_number() {
  27. assert!(luhn("4263 9826 4026 9299"));
  28. assert!(luhn("4539 3195 0343 6467"));
  29. assert!(luhn("7992 7398 713"));
  30. }
  31. #[test]
  32. fn test_invalid_cc_number() {
  33. assert!(!luhn("4223 9826 4026 9299"));
  34. assert!(!luhn("4539 3195 0343 6476"));
  35. assert!(!luhn("8273 1232 7352 0569"));
  36. }
  37. #[allow(dead_code)]
  38. fn main() {}