Skip to content

Instantly share code, notes, and snippets.

@laaptu
Created July 22, 2014 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laaptu/6625a5d4258a05f737b5 to your computer and use it in GitHub Desktop.
Save laaptu/6625a5d4258a05f737b5 to your computer and use it in GitHub Desktop.
Check whether a credit card number is valid or not? Valid credit card Number. Luhns algorithm
//http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Java
public static boolean isEmptyString(String stringValue) {
return stringValue == null || stringValue.trim().length() == 0;
}
public static boolean isCreditCardValid(String number) {
if (isEmptyString(number))
return false;
int s1 = 0, s2 = 0;
String reverse = new StringBuffer(number).reverse().toString();
for (int i = 0; i < reverse.length(); i++) {
int digit = Character.digit(reverse.charAt(i), 10);
if (i % 2 == 0) {// this is for odd digits, they are 1-indexed in
// the algorithm
s1 += digit;
} else {// add 2 * digit for 0-4, add 2 * digit - 9 for 5-9
s2 += 2 * digit;
if (digit >= 5) {
s2 -= 9;
}
}
}
return (s1 + s2) % 10 == 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment