【发布时间】: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,不,仍然有同样的问题