Last active
December 21, 2015 12:08
-
-
Save joohee/6303387 to your computer and use it in GitHub Desktop.
Luhn algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CreditCardValidation { | |
public static void main (String[] args) { | |
if (args.length < 1) { | |
System.out.println("usage: CreditCardValidation number"); | |
} else { | |
String cardNumber = args[0]; | |
int checksum = 0; | |
int length = cardNumber.length(); | |
for (int i = 0; i < length; i++) { | |
int num = Character.getNumericValue(cardNumber.charAt(length - (i+1))); | |
if (i % 2 == 1) { | |
int addedValue = num * 2; | |
if (addedValue > 10) { | |
int realAddedValue = (addedValue / 10 + addedValue % 10); | |
checksum += realAddedValue; | |
} else { | |
checksum += addedValue; | |
} | |
} else { | |
checksum += num; | |
} | |
} | |
System.out.println("value: " + checksum); | |
System.out.println("multiply 9 value: " + checksum * 9); | |
int realValue = (checksum * 9) % 10; | |
System.out.println("realValue: " + realValue); | |
int realValue2 = 0; | |
if (checksum % 10 == 0) { | |
realValue2 = 0; | |
} else { | |
realValue2 = ((checksum / 10 + 1) * 10 - checksum); | |
} | |
System.out.println("realValue2: " + realValue2); | |
if (realValue == realValue2) { | |
System.out.println("valid..."); | |
} else { | |
System.out.println("invalid..."); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment