@@ -10,54 +10,37 @@ namespace Algorithms.Other;
10
10
/// </summary>
11
11
public static class Luhn
12
12
{
13
- /// <summary>
14
- /// Checking the validity of a sequence of numbers.
15
- /// </summary>
16
- /// <param name="number">The number that will be checked for validity.</param>
17
- /// <returns>
18
- /// True: Number is valid.
19
- /// False: Number isn`t valid.
20
- /// </returns>
13
+ // Checking the validity of a sequence of numbers.
21
14
public static bool Validate ( string number ) => GetSum ( number ) % 10 == 0 ;
22
15
23
- /// <summary>
24
- /// This algorithm finds one missing digit.
25
- /// In place of the unknown digit, put "x".
26
- /// </summary>
27
- /// <param name="number">The number in which to find the missing digit.</param>
28
- /// <returns>Missing digit.</returns>
16
+ // Finds one missing digit. In place of the unknown digit, put "x".
29
17
public static int GetLostNum ( string number )
30
18
{
31
- var missingDigitIndex = number . Length - 1 - number . LastIndexOf ( "x" , StringComparison . CurrentCultureIgnoreCase ) ;
32
- var checkDigit = GetSum ( number . Replace ( "x" , "0" , StringComparison . CurrentCultureIgnoreCase ) ) * 9 % 10 ;
33
-
34
- // Case 1: If the index of the missing digit is even.
35
- if ( missingDigitIndex % 2 == 0 )
36
- {
37
- return checkDigit ;
38
- }
39
-
40
- var candidateDigit = checkDigit / 2 ;
41
-
42
- // Case 2: if the index of the missing digit is odd and the candidate is valid.
43
- // Case 3: if the index of the missing digit is odd and we need the alternative.
44
- return Validate ( number . Replace ( "x" , candidateDigit . ToString ( ) ) ) ? candidateDigit : ( checkDigit + 9 ) / 2 ;
19
+ var missingDigitIndex = number . Length - 1 - number . LastIndexOf ( 'x' ) ;
20
+ var checkDigit = GetSum ( number . Replace ( "x" , "0" ) ) * 9 % 10 ;
21
+
22
+ return missingDigitIndex % 2 == 0
23
+ ? checkDigit
24
+ : Validate ( number . Replace ( "x" , ( checkDigit / 2 ) . ToString ( ) ) )
25
+ ? checkDigit / 2
26
+ : ( checkDigit + 9 ) / 2 ;
45
27
}
46
28
47
- /// <summary>
48
- /// Computes the sum found by the Luhn algorithm.
49
- /// </summary>
50
- /// <param name="number">The number for which the sum will be calculated.</param>
51
- /// <returns>Sum.</returns>
29
+ // Computes the sum found by the Luhn algorithm, optimized with Span.
52
30
private static int GetSum ( string number )
53
31
{
54
32
var sum = 0 ;
55
- for ( var i = 0 ; i < number . Length ; i ++ )
33
+ var span = number . AsSpan ( ) ;
34
+ for ( var i = 0 ; i < span . Length ; i ++ )
56
35
{
57
- var digit = number [ i ] - '0' ;
58
- digit = ( i + number . Length ) % 2 == 0
59
- ? 2 * digit
60
- : digit ;
36
+ var c = span [ i ] ;
37
+ if ( c is < '0' or > '9' )
38
+ {
39
+ continue ;
40
+ }
41
+
42
+ var digit = c - '0' ;
43
+ digit = ( i + span . Length ) % 2 == 0 ? 2 * digit : digit ;
61
44
if ( digit > 9 )
62
45
{
63
46
digit -= 9 ;
0 commit comments