How do I implement the Luhn algorithm?

后端 未结 8 1609
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 09:50

I am trying to create a program to validate 10 to 12 digit long number sequences based on the luhn algorithm, but my program keeps on telling me that every number is invalid

8条回答
  •  旧时难觅i
    2020-12-21 10:14

    If you use Java 10 or higher, you can use the following code:

    public static boolean luhn(String s) {
        IntUnaryOperator sumDigits = n -> n / 10 + n % 10;
        var digits = s.chars()
                      .map(Character::getNumericValue)
                      .toArray();
        return IntStream.rangeClosed(1, digits.length)
                        .map(i -> digits.length - i)
                        .map(i -> i % 2 == 0 ? digits[i] : sumDigits.applyAsInt(digits[i] * 2))
                        .sum() % 10 == 0;
    }
    

    It's the functional approach to this algorithm.

提交回复
热议问题