标签:
http://stackoverflow.com/questions/26383926/luhn-algorithm-java
1 static boolean luhn(String pnr){ 2 // this only works if you are certain all input will be at least 10 characters 3 int extraChars = pnr.length() - 10; 4 if (extraChars < 0) { 5 throw new IllegalArgumentException("Number length must be at least 10 characters!"); 6 } 7 pnr = pnr.substring(extraChars, 10 + extraChars); 8 int sum = 0; 9 for (int i = 0; i < pnr.length(); i++){ 10 char tmp = pnr.charAt(i); 11 int num = tmp - ‘0‘; 12 int product; 13 if (i % 2 != 0){ 14 product = num * 1; 15 } 16 else{ 17 product = num * 2; 18 } 19 if (product > 9) 20 product -= 9; 21 sum+= product; 22 } 23 return (sum % 10 == 0); 24 } 25 26 private static void printMessage(boolean valid) { 27 if (valid){ 28 System.out.print("Valid!\r"); 29 } 30 else{ 31 System.out.print("Invalid!"); 32 } 33 } 34 }
标签:
原文地址:http://www.cnblogs.com/kelisi-king/p/4272322.html