gpt4 book ai didi

c# - 如何在 C# 中检查加拿大社会保险号的有效性?

转载 作者:太空狗 更新时间:2023-10-29 20:11:45 24 4
gpt4 key购买 nike

我的任务是用 C# 编写算法来检查加拿大社会保险号 (SIN) 的有效性。以下是验证 SIN 的步骤。

给出一个例子号码:123 456 782

  1. 去掉校验位(最后一位):123456782
  2. 提取偶数位(第2、4、6、8位):1234567 8
  3. 加倍:
        2  4  6  8    |  |  |  |    v  v  v  v    4  8  12 16 
  4. 将数字相加:
    4+8+1+2+1+6 = 22
  5. 添加奇数位:
        1+3+5+7 = 16
          Total : 38

有效性算法

  1. 如果总数是 10 的倍数,则校验位应为零。
  2. 否则,从下一个最大的 10 倍数(在本例中为 40)中减去总数
  3. 此 SIN 的校验位必须等于该数字与之前总数的差值(在本例中,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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com