I created LINQ implementation of mod10 algorithm.
The source code:
string number = "7992739871";
int mod10sum = number.Reverse()
.Select((c, i) => (c - '0') << ((i + 1) & 1)) // Double every other digit and sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5)
.Sum(c => c - '0') % 10; // together with the undoubled digits from the original number
string checkDigit = (mod10sum == 0 ? 0 : 10 - mod10sum).ToString("0");
Console.WriteLine(checkDigit);
As per the example, 7992739871 number should have check digit as 3; however, what I am getting is 15.
What I am doing wrong? I am sure the mistake is very small but can’t find it.
I would change the
Sum.At this point, you don’t have a sequence of characters, but the single-or-doubled-as-appropriate value for each original digit.
Thus, you don’t need to be subtracting
0, you need to be calculating the digit sum of each of these integers, and (since you know they’ll be small) you can do this as simply asgiving
This should be more effecient than calling
ToString()and iterating over the result.