卡号规则

  1. 从卡号最后一位数字开始,逆向将奇数位(135等等)相加。
  2. 从卡号最后一位数字开始,逆向将偶数位数字,先乘以2(如果乘积为两位数,则将其减去9),再求和。
  3. 将奇数位总和加上偶数位总和,结果应该可以被10整除。

代码示例(JAVA)----校验卡号的合法性

public static void main(String[] args) {
    String cardId = "5432123456788881";
    if(cardId == null || cardId.trim().length() == 0
            || !cardId.matches("\\d+")||cardId.trim().length()<15
            ||cardId.trim().length()>18) {
        System.out.println("银行卡号不合法!");

return;
    }
    char[] chars = cardId.trim().toCharArray();
    int i = chars.length-1;
    System.out.println(i);
    int sum = 0;
    //从最后一位数对奇数位和偶数位上的数字进行操作
    while (i >= 0){
        if (i%2 != 0){
            //将字符按10进制数显示并且加到sum上
            sum += Character.digit(chars[i], 10);
        }else {
            //将字符按10进制展示乘2
            int n = Character.digit(chars[i], 10) * 2;
            //如果所得结果小于9直接加到sum上否则将结果减去9再加到sum上
            if (n > 9) n -= 9;
            sum += n;
        }
        i--;
    }
    System.out.println("总和:"+sum);
    System.out.println(sum % 10 == 0 ? true : false);
}

代码示例(JAVA)----生成卡号的校验位

    private static Character getCheckNum(){
        //不含校验位的卡号
        String carId = "543212 345678888";
        carId = carId.replace(" ", "" );
        int sum = 0;
        char[] chars = carId.trim().toCharArray();
        int i = chars.length-1;
        while (i >= 0){
            if (i % 2 != 0) sum += Character.digit(chars[i], 10);
            else {
                int n = Character.digit(chars[i], 10) * 2;
                if (n > 9){
                    n = n/10 + n%10;
                }
                sum += n;
            }
            i--;
        }
        return (sum % 10 == 0)? '0' : (char)((10-sum % 10)+'0');
    }
}