lots of exercises in java... from https://github.com/exercism/java

LuhnValidator.java 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.regex.Pattern;
  4. final class LuhnValidator {
  5. private static final Pattern SPACE_PATTERN = Pattern.compile("\\s+");
  6. boolean isValid(final String candidate) {
  7. final String sanitizedCandidate = SPACE_PATTERN.matcher(candidate).replaceAll("");
  8. final List<Integer> computedDigits = new ArrayList<>();
  9. for (int charIndex = 0; charIndex < sanitizedCandidate.length(); charIndex++) {
  10. int inputDigit = Character.digit(sanitizedCandidate.charAt(charIndex), 10);
  11. /*
  12. * Character.digit returns a negative int if the supplied character does not represent a digit with respect
  13. * to the given radix.
  14. */
  15. if (inputDigit < 0) {
  16. return false;
  17. }
  18. if (charIndex % 2 == 1) {
  19. /*
  20. * Since our doubled input digit must lie in [2, 18], the operation
  21. *
  22. * "subtract 9 from the doubled input digit if it exceeds 9 in value"
  23. *
  24. * is equivalent to applying the modulo operation below universally.
  25. */
  26. inputDigit = (2 * inputDigit) % 9;
  27. }
  28. computedDigits.add(inputDigit);
  29. }
  30. final int digitSum = computedDigits.stream().mapToInt(Integer::intValue).sum();
  31. return digitSum > 0 && digitSum % 10 == 0;
  32. }
  33. }