练习:卢恩算法
卢恩算法
卢恩算法用于验证信用卡号。该算法将字符串作为输入内容,并执行以下操作来验证信用卡号:
- Ignore all spaces. Reject number with fewer than two digits.
- 从右到左,将偶数位的数字乘二。对于数字“1234”,我们将“3”和“1”乘二;对于数字“98765”,将“6”和“8”乘二。
- 将一个数字乘二后,如果结果大于 9,则将每位数字相加。因此,将“7”乘二得“14”,然后“1 + 4 = 5”。
- 将所有未乘二和已乘二的数字相加。
- 如果总和以“0”结尾,则信用卡号有效。
提供的代码提供了一个有缺陷的 Luhn 算法实现,附带两个基本单元测试,用于验证大部分算法是否正确实现。
Copy the code below to <https://play.rust-lang.org/> and write additional tests to uncover bugs in the provided implementation, fixing any bugs you find.
1. #![allow(unused)]
2. fn main() {
3. pub fn luhn(cc_number: &str) -> bool {
4. let mut sum = 0;
5. let mut double = false;
7. for c in cc_number.chars().rev() {
8. if let Some(digit) = c.to_digit(10) {
9. if double {
10. let double_digit = digit * 2;
11. sum +=
12. if double_digit > 9 { double_digit - 9 } else { double_digit };
13. } else {
14. sum += digit;
15. }
16. double = !double;
17. } else {
18. continue;
19. }
20. }
22. sum % 10 == 0
23. }
25. #[cfg(test)]
26. mod test {
27. use super::*;
29. #[test]
30. fn test_valid_cc_number() {
31. assert!(luhn("4263 9826 4026 9299"));
32. assert!(luhn("4539 3195 0343 6467"));
33. assert!(luhn("7992 7398 713"));
34. }
36. #[test]
37. fn test_invalid_cc_number() {
38. assert!(!luhn("4223 9826 4026 9299"));
39. assert!(!luhn("4539 3195 0343 6476"));
40. assert!(!luhn("8273 1232 7352 0569"));
41. }
42. }
43. }
