首页 > 编程语言 >Rust实现Luhn算法

Rust实现Luhn算法

时间:2022-12-25 18:22:05浏览次数:64  
标签:10 ch return sum 算法 let false Luhn Rust

什么是Luhn算法?

pub fn luhn(cc_number: &str) -> bool {
    //scan number from right to left, the digit *2 which in every second position
    if cc_number.is_empty() {
        return false;
    }
    let chats = cc_number.chars();
    let mut sum = 0;
    let mut digits_seen = 0;
    for (index, ch) in chats.rev().filter(|&ch| ch != ' ').enumerate() {
        let mut num_ch = ch.to_digit(10);
        match num_ch {
            Some(d) => {
                if (index + 1) % 2 == 0 {
                    let n = d * 2;
                    if n < 10 {
                        sum += n;
                    } else {
                        sum += n % 10 + n / 10;
                    }
                } else {
                    sum += d;
                }
                digits_seen += 1;
            }
            None => return false
        }
    }
    //return false if digits count less than 2
    if digits_seen < 2 {
        return false;
    }
    return sum % 10 == 0;
}

 

 

标签:10,ch,return,sum,算法,let,false,Luhn,Rust
From: https://www.cnblogs.com/johnnyzhao/p/17004347.html

相关文章