作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的任务是用 C# 编写算法来检查加拿大社会保险号 (SIN) 的有效性。以下是验证 SIN 的步骤。
给出一个例子号码:123 456 782
2 4 6 8 | | | | v v v v 4 8 12 16
4+8+1+2+1+6 = 22
1+3+5+7 = 16
Total : 38
有效性算法
40-38 = 2
;校验位为 2,因此该数字为有效)我不知道如何在 C# 中实际实现它,我该怎么做?
最佳答案
这是一个很好解决的问题。这应该比转换为字符串并解析回整数更有效。此解决方案适用于 .NET 3.5 及更高版本。
public static IEnumerable<int> ToDigitEnumerable(this int number)
{
IList<int> digits = new List<int>();
while(number > 0)
{
digits.Add(number%10);
number = number/10;
}
//digits are currently backwards, reverse the order
return digits.Reverse();
}
public static bool IsCanadianSocialInsuranceNumber(int number)
{
var digits = number.ToDigitEnumerable();
if (digits.Count() != 9) return false;
//The left side of the addition is adding all even indexes (except the last digit).
//We are adding even indexes since .NET uses base 0 for indexes
//The right side of the addition, multiplies the odd index's value by 2, then breaks each result into
//individual digits, then adds them together
var total = digits.Where((value, index) => index%2 == 0 && index != 8).Sum()
+ digits.Where((value, index) => index%2 != 0).Select(v => v*2)
.SelectMany(v => v.ToDigitEnumerable()).Sum();
//The final modulous 10 operator is to handle the scenarios where the total
//is divisble by 10, in those cases, the check sum should be 0, not 10
var checkDigit = (10 - (total%10)) % 10;
return digits.Last() == checkDigit;
}
此解决方案的一个问题是它假定表示为整数的数字为 9 位数字(不能以 0 开头)。如果数字可以以 0 开头,则它必须表示为字符串(或转换为字符串并用零填充)。要测试的逻辑将大部分保持不变,但假定整数的部分需要用字符串换出,然后您必须进行解析。
关于c# - 如何在 C# 中检查加拿大社会保险号的有效性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4263398/
我是一名优秀的程序员,十分优秀!