【问题标题】:luhn algorithm with spaced strings as input c#以间隔字符串作为输入c#的luhn算法
【发布时间】:2021-07-08 11:58:21
【问题描述】:

尝试实现一个 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” 我可以编辑什么来消除这个错误?

【问题讨论】:

  • (int)(cardNo[i]) 不是数字...它是 ascii/char 值,例如 '1' 49
  • docs.microsoft.com/de-de/dotnet/api/… 检查它是否是一个数字,如果你想要 int 值,你需要先转换为字符串或使用 int.Parse
  • cardNo = cardNo.Replace(" ", ""); 怎么样? (假设你想去掉每一个空格,空格可以在任何地方)
  • @gunr2171,不,仍然有同样的问题

标签: c# trim luhn


【解决方案1】:

在你的情况下,我不明白为什么你不能只使用 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 等等。

【讨论】:

    【解决方案2】:

    @Rafalon 提出了这个问题的正确答案

    在每个字符串读取后添加一个 Replace(" ", "") 函数

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 2021-09-04
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      相关资源
      最近更新 更多