How do I implement the Luhn algorithm?

后端 未结 8 1604
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  攒了一身酷
    2020-12-21 10:11

    I use this function in an app for checking card number validity :

    public static boolean Check(String ccNumber)
        {
                int sum = 0;
                boolean alternate = false;
                for (int i = ccNumber.length() - 1; i >= 0; i--)
                {
                        int n = Integer.parseInt(ccNumber.substring(i, i + 1));
                        if (alternate)
                        {
                                n *= 2;
                                if (n > 9)
                                {
                                        n = (n % 10) + 1;
                                }
                        }
                        sum += n;
                        alternate = !alternate;
                }
                return (sum % 10 == 0);
        }
    

    Hope it helps,

提交回复
热议问题