@@ -10,54 +10,37 @@ namespace Algorithms.Other;
1010/// </summary>
1111public static class Luhn
1212{
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.
2114 public static bool Validate ( string number ) => GetSum ( number ) % 10 == 0 ;
2215
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".
2917 public static int GetLostNum ( string number )
3018 {
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 ;
4527 }
4628
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.
5230 private static int GetSum ( string number )
5331 {
5432 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 ++ )
5635 {
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 ;
6144 if ( digit > 9 )
6245 {
6346 digit -= 9 ;
0 commit comments