码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA LUHN

时间:2015-02-04 16:15:06      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

 

JAVA LUHN

标签:

原文地址:http://www.cnblogs.com/kelisi-king/p/4272322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!