盧恩演算法
盧恩演算法
盧恩演算法可用於驗證信用卡號碼。這個演算法會將字串做為輸入內容,並執行下列操作來驗證信用卡號碼:
-
Ignore all spaces. Reject number with fewer than two digits.
-
從右到左,將偶數位的數字乘二。以數字
1234為例,請將3和1乘二;若為數字98765,請將6和8乘二。 -
將數字乘二後,如果結果大於 9,請將每位數字相加。所以,
7乘二等於14,那麼也就是1 + 4 = 5。 -
將所有數字 (無論是否已乘二) 相加。
-
如果加總所得數字的末位是
0,代表信用卡卡號有效。
這裡提供的程式碼是盧恩演算法的錯誤實作示例,另外還有兩個基本單元測試,用於確認大部分演算法已正確實作。
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.
#![allow(unused)]
fn main() {
pub fn luhn(cc_number: &str) -> bool {
let mut sum = 0;
let mut double = false;
for c in cc_number.chars().rev() {
if let Some(digit) = c.to_digit(10) {
if double {
let double_digit = digit * 2;
sum +=
if double_digit > 9 { double_digit - 9 } else { double_digit };
} else {
sum += digit;
}
double = !double;
} else {
continue;
}
}
sum % 10 == 0
}
#[cfg(test)]
mod test {
use super::*;
#[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"));
}
}
}