首页 > 编程语言 > 详细

JAVA LUHN

时间:2015-02-04 16:14:45      阅读:348      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!