Tuesday, February 02, 2010

Credit Card Mod10 Validation

The follow code was got from WikiPedia and did a little modification. It is very neat and elegant.

public static boolean isValidCC(String num) {
  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 = num.length() - 1; i >= 0; i--, flip++){
    int n = num.charAt(i) - '0';
    if (n < 0 || n > 9)
      return false;
    sum += sumTable[flip & 0x1][n];
  }
  return (sum == 0) ? false : (sum % 10 == 0);
}


The follow code used a variable as a switch to double the value.

public static boolean isValidCC(String number) {
  int sum = 0;
  int mul = 1;
  for (int i = number.length() - 1; i >= 0; i--) {
    int n = number.charAt(i) - '0';
    if (n < 0 || n > 9)
      return false;
    n *= (mul == 1) ? mul++ : mul--;
    sum += (n>9 ? n-9 : n);
  }
  return (sum == 0) ? false : (sum % 10 == 0);
}


The follow code used the position to double the value.

public static boolean isValidCC(String number) {
  int sum = 0;
  for (int i = number.length() - 1; i >= 0; i--) {
    int n = number.charAt(i) - '0';
    if (n < 0 || n > 9)
      return false;
    if ((number.length()-i)%2 == 0)
      n *= 2;
    sum += (n>9 ? n-9 : n);
  }
  return (sum == 0) ? false : (sum % 10 == 0);
}


The follow code used any way to double the value.

protected boolean isValidCC(String number) {
  int digits = number.length();
  int oddOrEven = digits & 1;
  long sum = 0;
  for (int i= 0; i < digits; i++) {
    int n = number.charAt(count) -'0';
    if (n < 0 || n > 9)
      return false;
    if (((i& 1) ^ oddOrEven) == 0)
      n *= 2;
    sum += (n>9 ? n-9 : n);
  }
  return (sum == 0) ? false : (sum % 10 == 0);
}


The follow code much easier to understand.

public static boolean isValidCC(String number) {
  int sum = 0;
  boolean alternate = false;
  for (int i = number.length() - 1; i >= 0; i--) {
    int n = Integer.parseInt(number.substring(i, i + 1)); //May throw out a runtime exception
    if (alternate) {
      n *= 2;
    sum += (n>9 ? (n%10)+1 : n);
    alternate = !alternate;
  }
  return (sum == 0) ? false : (sum % 10 == 0);
}

No comments: