银行卡luhm校验算法

 1   /**
 2      * 15位银行卡luhm校验算法
 3      * 1、从卡号最后一位数字开始,逆向将奇数位(1、3、5等等)相加。
 4      * 2、从卡号最后一位数字开始,逆向将偶数位数字,先乘以2(如果乘积为两位数,则将其减去9),再求和。
 5      * 3、将奇数位总和加上偶数位总和,结果应该可以被10整除。
 6      * @param temp 前15位
 7      * @return  有效卡返回原卡号,无效卡返回空字符串
 8      */
 9     public static String luhm(String temp) {
10         String result = "";
11         String reg15Nums = "^\d{15}$";// 15 位数字
12         if (temp.matches(reg15Nums)) {
13             char[] ns = temp.toCharArray();
14             int numSum = 0;
15             for (int i = ns.length - 1, j = 0; i >= 0; i--, j++) {
16                 char n = ns[i];
17                 int num = Integer.parseInt(n + "");
18                 if (j % 2 == 0) {
19                     num *= 2;
20                     if (num > 9) {
21                         num -= 9;
22                     }
23                 }
24                 numSum += num;
25             }
26             int last = (10 - numSum % 10) % 10;
27             result = temp + last;
28         }
29         return result;
30     }

下面附上16到19位之间的luhm校检的js代码案例

16到19位之间的银行卡号luhm校验JS代码.zip

原文地址:https://www.cnblogs.com/tfgzs/p/3644687.html