|
|
@@ -9,10 +9,17 @@ final class LuhnValidator {
|
|
9
|
9
|
boolean isValid(final String candidate) {
|
|
10
|
10
|
final String sanitizedCandidate = SPACE_PATTERN.matcher(candidate).replaceAll("");
|
|
11
|
11
|
|
|
|
12
|
+ if (sanitizedCandidate.length() <= 1) {
|
|
|
13
|
+ return false;
|
|
|
14
|
+ }
|
|
|
15
|
+
|
|
|
16
|
+ // We need to alter every second digit counting from the right. Reversing makes this easy!
|
|
|
17
|
+ final String reversedSanitizedCandidate = reverse(sanitizedCandidate);
|
|
|
18
|
+
|
|
12
|
19
|
final List<Integer> computedDigits = new ArrayList<>();
|
|
13
|
20
|
|
|
14
|
|
- for (int charIndex = 0; charIndex < sanitizedCandidate.length(); charIndex++) {
|
|
15
|
|
- int inputDigit = Character.digit(sanitizedCandidate.charAt(charIndex), 10);
|
|
|
21
|
+ for (int charIndex = 0; charIndex < reversedSanitizedCandidate.length(); charIndex++) {
|
|
|
22
|
+ int inputDigit = Character.digit(reversedSanitizedCandidate.charAt(charIndex), 10);
|
|
16
|
23
|
|
|
17
|
24
|
/*
|
|
18
|
25
|
* Character.digit returns a negative int if the supplied character does not represent a digit with respect
|
|
|
@@ -23,21 +30,22 @@ final class LuhnValidator {
|
|
23
|
30
|
}
|
|
24
|
31
|
|
|
25
|
32
|
if (charIndex % 2 == 1) {
|
|
26
|
|
- /*
|
|
27
|
|
- * Since our doubled input digit must lie in [2, 18], the operation
|
|
28
|
|
- *
|
|
29
|
|
- * "subtract 9 from the doubled input digit if it exceeds 9 in value"
|
|
30
|
|
- *
|
|
31
|
|
- * is equivalent to applying the modulo operation below universally.
|
|
32
|
|
- */
|
|
33
|
|
- inputDigit = (2 * inputDigit) % 9;
|
|
|
33
|
+ inputDigit = 2 * inputDigit;
|
|
|
34
|
+
|
|
|
35
|
+ if (inputDigit > 9) {
|
|
|
36
|
+ inputDigit -= 9;
|
|
|
37
|
+ }
|
|
34
|
38
|
}
|
|
35
|
39
|
|
|
36
|
40
|
computedDigits.add(inputDigit);
|
|
37
|
41
|
}
|
|
38
|
42
|
|
|
39
|
43
|
final int digitSum = computedDigits.stream().mapToInt(Integer::intValue).sum();
|
|
40
|
|
- return digitSum > 0 && digitSum % 10 == 0;
|
|
|
44
|
+ return digitSum % 10 == 0;
|
|
|
45
|
+ }
|
|
|
46
|
+
|
|
|
47
|
+ private String reverse(final String string) {
|
|
|
48
|
+ return new StringBuilder(string).reverse().toString();
|
|
41
|
49
|
}
|
|
42
|
50
|
|
|
43
|
51
|
}
|