Check Credit Card Validity using Luhn Algorithm

前端 未结 12 1573
刺人心
刺人心 2020-12-03 04:02

I tried to check the validation of credit card using Luhn algorithm, which works as the following steps:

  1. Double every second digit from right to left. If do

12条回答
  •  眼角桃花
    2020-12-03 04:22

    I took a stab at this with Java 8:

    public static boolean luhn(String cc) {
        final boolean[] dbl = {false};
        return cc
                .chars()
                .map(c -> Character.digit((char) c, 10))
                .map(i -> ((dbl[0] = !dbl[0])) ? (((i*2)>9) ? (i*2)-9 : i*2) : i)
                .sum() % 10 == 0;
    }
    

    Add the line

                .replaceAll("\\s+", "")
    

    Before

                .chars()
    

    If you want to handle whitespace.

    Seems to produce identical results to

    return LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(cc);
    

    From Apache's commons-validator.

提交回复
热议问题