How do I implement the Luhn algorithm?

后端 未结 8 1625
被撕碎了的回忆
被撕碎了的回忆 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:20

    Newcomers to this post/question can check appropriate Wikipedia page for solution. Below is the Java code copy-pasted from there.

    public class Luhn
    {
            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);
            }
    }
    

提交回复
热议问题