What's wrong with my Luhn algorithm code?
I'm trying to use this code to test if a sample code is a valid credit card number or not (using the Luhn algorithm) in Java. Where did I go wrong? It takes in an array of 16 one-digit numbers. Any help would be much appreciated. T开发者_如何学Pythonhanks!
private static boolean isValidCC(int[] number) {
int sum = 0;
boolean alternateNum = true;
for (int i = number.length-1; i>=0; i--) {
int n = number[i];
if (alternateNum) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternateNum = !alternateNum;
}
System.out.println(sum);
return (sum % 10 == 0);
}
Your code is correct except you started with the wrong alternate digit. Change to:
boolean alternateNum = false;
Judging from Wikipedia article --you've missed a checksum digit or erroneously taking it into account--.
Update: most probably, you've started with a wrong "alternate" flag.
There is a Java snippet, so why not use it?
public static boolean isValidCC(String number) {
final int[][] sumTable = {{0,1,2,3,4,5,6,7,8,9},{0,2,4,6,8,1,3,5,7,9}};
int sum = 0, flip = 0;
for (int i = number.length() - 1; i >= 0; i--) {
sum += sumTable[flip++ & 0x1][Character.digit(number.charAt(i), 10)];
}
return sum % 10 == 0;
}
Alternating digits are doubled counting from the end not the beginning.
instead of using your alternateNum
bool try this.
if((number.length - i) % 2 == 0){
n *= 2;
...
}
精彩评论