银行卡 Luhn check

1:该校验的过程:

   1、从卡号最后一位数字开始,逆向将奇数位(135等等)相加。

   2、从卡号最后一位数字开始,逆向将偶数位数字,先乘以2(如果乘积为两位数,则将其减去9),再求和。

   3、将奇数位总和加上偶数位总和,结果应该可以被10整除。

2:代码

public static boolean luhnCheck(String number) {
        int s1 = 0, s2 = 0;
        String reverse = new StringBuffer(number).reverse().toString();
        for(int i = 0 ;i < reverse.length();i++){
            int digit = Character.digit(reverse.charAt(i), 10);
            if(i % 2 == 0){//this is for odd digits, they are 1-indexed in the algorithm
                s1 += digit;
            }else{//add 2 * digit for 0-4, add 2 * digit - 9 for 5-9
                s2 += 2 * digit;
                if(digit >= 5){
                    s2 -= 9;
                }
            }
        }
        return (s1 + s2) % 10 == 0;
    }

猜你喜欢

转载自www.cnblogs.com/wnpp/p/12096315.html