![luhn checksum calculator luhn checksum calculator](https://www.101computing.net/wp/wp-content/uploads/Luhn-Algorithm-253x300.png)
when checking a string for a missing character, return a char rather than an int.
#Luhn checksum calculator code
#Luhn checksum calculator mod
Return ((validCodePointCount - (sum %= validCodePointCount)) % validCodePointCount) ġ0 - (x mod 10) can never exceed 10, so the last modulo operation is completely unnecessary. if ((validCodePointCount - 1) = digit % + 1 While we are at it, there is no argument guard that ensures value will always be a string of digits.Įdit: If you look to support an arbitrary set of characters, you can use a lookup table to map the character to its "numerical" value. while (0 48Ī int.Parse could be used instead. You can then iterate forward: foreach (int n in value.Select(c => c - '0'))Ĭonstants should be written in PascalCase, whether it is private or local. You don't have to iterate backwards because you can determine the initial parity from the length of the input string: var parity = value.Length % 2 != 0 In general it is wise to avoid magic numbers, but in some situations it is preferable in order to improve readability - IMO. This is such a common operation and we all know what it's about immediately when seeing it. In fact in such a relatively small algorithm, I would prefer to use the literals directly in the code than the named constants like: var digit = (value - '0') Here I use '0' instead of 48 because the first is much more recognizable to programmers than the latter, and we instantly grasp the meaning. The names of these constants are hard to distinguish from each other and to understand in the context and they blur the behavior of the algorithm.īetter names could be: const int numberBase = 10