@@ -21,49 +21,49 @@ public static class Luhn
21
21
public static bool Validate ( string number ) => GetSum ( number ) % 10 == 0 ;
22
22
23
23
/// <summary>
24
- /// This algorithm only finds one number .
24
+ /// This algorithm finds one missing digit .
25
25
/// In place of the unknown digit, put "x".
26
26
/// </summary>
27
27
/// <param name="number">The number in which to find the missing digit.</param>
28
28
/// <returns>Missing digit.</returns>
29
29
public static int GetLostNum ( string number )
30
30
{
31
- var lostIndex = number . Length - 1 - number . LastIndexOf ( "x" , StringComparison . CurrentCultureIgnoreCase ) ;
32
- var lostNum = GetSum ( number . Replace ( "x" , "0" , StringComparison . CurrentCultureIgnoreCase ) ) * 9 % 10 ;
31
+ var missingDigitIndex = number . Length - 1 - number . LastIndexOf ( "x" , StringComparison . CurrentCultureIgnoreCase ) ;
32
+ var checkDigit = GetSum ( number . Replace ( "x" , "0" , StringComparison . CurrentCultureIgnoreCase ) ) * 9 % 10 ;
33
33
34
- // Case 1: If the index of the lost digit is even.
35
- if ( lostIndex % 2 == 0 )
34
+ // Case 1: If the index of the missing digit is even.
35
+ if ( missingDigitIndex % 2 == 0 )
36
36
{
37
- return lostNum ;
37
+ return checkDigit ;
38
38
}
39
39
40
- var tempLostNum = lostNum / 2 ;
40
+ var candidateDigit = checkDigit / 2 ;
41
41
42
- // Case 2: if the index of the lost digit isn`t even and that number <= 4 .
43
- // Case 3: if the index of the lost digit isn`t even and that number > 4 .
44
- return Validate ( number . Replace ( "x" , tempLostNum . ToString ( ) ) ) ? tempLostNum : ( lostNum + 9 ) / 2 ;
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 ;
45
45
}
46
46
47
47
/// <summary>
48
- /// Computes the sum found by the algorithm.
48
+ /// Computes the sum found by the Luhn algorithm.
49
49
/// </summary>
50
- /// <param name="number">The number for which the sum will be found .</param>
50
+ /// <param name="number">The number for which the sum will be calculated .</param>
51
51
/// <returns>Sum.</returns>
52
52
private static int GetSum ( string number )
53
53
{
54
54
var sum = 0 ;
55
55
for ( var i = 0 ; i < number . Length ; i ++ )
56
56
{
57
- var d = number [ i ] - '0' ;
58
- d = ( i + number . Length ) % 2 == 0
59
- ? 2 * d
60
- : d ;
61
- if ( d > 9 )
57
+ var digit = number [ i ] - '0' ;
58
+ digit = ( i + number . Length ) % 2 == 0
59
+ ? 2 * digit
60
+ : digit ;
61
+ if ( digit > 9 )
62
62
{
63
- d -= 9 ;
63
+ digit -= 9 ;
64
64
}
65
65
66
- sum += d ;
66
+ sum += digit ;
67
67
}
68
68
69
69
return sum ;
0 commit comments