首页 > 解决方案 > 以间隔字符串作为输入c#的luhn算法

问题描述

尝试实现 luhn 算法,但使用间隔字符串作为输入。我已经尝试过 Linq,一些可能与其直接相关的预定义字符串函数(Trim()、Replace()),但它并没有打印出正确的答案

这是我的代码:

static bool checkCard(string cardNo)    
{   
    
    
    int[] cardInt = new int[cardNo.Length];
    for(int i = 0;i < cardNo.Length; i++){
        cardInt[i] = (int)(cardNo[i]);
    }
    for(int i = cardNo.Length - 2;i >= 0;i-=2){
        int temporaryValue = cardInt[i];
        temporaryValue*=2;
        if(temporaryValue > 9){
            temporaryValue = temporaryValue % 10 +1;
        }
        cardInt[i] = temporaryValue;
    }
    int sum = 0;
    for(int i = 0;i<cardNo.Length;i++){
        sum+=cardInt[i];
    }
    if(sum % 10 == 0){
        return true;
    }
        
    return false;
    
}
static void Main(string[] args)
{
    
    int n = int.Parse(Console.ReadLine());
    for (int i = 0; i < n; i++)
    {
        string card = Console.ReadLine();
        
        if (checkCard(card))
        Console.WriteLine("YES");
        else
        Console.WriteLine("NO");
        
    }

}

输入:4556 7375 8689 9855

输出必须是“YES”但它会打印“NO”我可以编辑什么才能摆脱这个错误?

标签: c#trimluhn

解决方案


在您的情况下,我不明白为什么您不能只使用 char.IsDigit() ,因为信用卡号不是字母数字,这里有一个简短的 linq 示例:

        var digitsOnly = cardNo.Where(x => char.IsDigit(x)).ToArray();
        int[] integersArray = digitsOnly.Select( x = int.Parse(x.ToString())).ToArray();  

顺便说一句,如果你将 char 转换为 int,你会得到它的 ASCII intvalue,所以 0 是 48,1 是 49 等等。


推荐阅读