LUHN 模10 算法 银行卡校验


信用卡Luhn算法(模10)具体的校验过程如下:

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

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

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

例如,卡号是:5432123456788881

则奇数、偶数位分布:5432123456788881

奇数位和=35

偶数位乘以2(有些要减去9)的结果:1 6 2 6 1 5 7 7,求和=35。

最后35+35=70 可以被10整除,认定校验通过。

java代码

	public static boolean luhnValidate(String cardNo) {
		if(null == cardNo || cardNo.length() == 0) {
			return true;
		}
		
		if(null == cardNo || cardNo.matches("[0-9]*")) {
			return false;
		}
		
		int result = 0;
		int digit = 0;
		int counter = 0;
		for(int i = cardNo.length()-2; i >= 0; i--) {
			digit = Character.digit(cardNo.charAt(i), 10);
			if((counter % 2) == 0) {
				digit *= 2;
				result += (digit/10 + digit%10);
			} else {
				result += digit;
			}
			counter++;
		}
		
		return (10 - result%10) == Character.digit(cardNo.charAt(cardNo.length()-1), 10);
	}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM