c# - 以间隔字符串作为输入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”我可以编辑什么才能摆脱这个错误?
解决方案
在您的情况下,我不明白为什么您不能只使用 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 等等。
推荐阅读
- python - Pandas:处理具有多种数据类型的列
- python - 如何在 Python 中组合 CSV?
- javascript - document.hasOwnProperty("hidden") 返回 false,但 document 的属性为 hidden
- angular - 将 Angular 材质添加到现有 Angular 7 应用程序时出错
- java - 如何将 SSL 证书添加到 cacerts 和 keystore?
- android - 如何将可访问性焦点转移到 RecyclerView 在某些操作上的第一个元素上?
- ruby-on-rails - JqueryUI Autocomplete 不是 Rails 5 中的功能
- android - 无法使用 Glide/Fresco 加载图像
- python - Join All dataframes which names starts with df
- postgresql - 使用 db.create_all() 运行迁移