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