luhn算法

package cn.com.wuzhq.digui;

/**
** 发卡机构标识码(bin)(6位)+ 发卡机构自定义位(6~12位)+ 校验码(1位)
**/
public class Luhn {
	 /**  
	     * Luhn算法  
	     * 根据卡号获取校验位  
	     * @param cardNumber  
	     * @return  
	     */  
	    public static int getCheckNumber(String cardNumber){  
	        int totalNumber = 0;  
	        for (int i = cardNumber.length()-1; i >= 0; i-=2) {  
	            int tmpNumber = calculate(Integer.parseInt(String.valueOf(cardNumber.charAt(i))) *  2);  
	            if (i==0) {  
	                totalNumber += tmpNumber;  
	            }else {  
	                totalNumber += tmpNumber + Integer.parseInt(String.valueOf(cardNumber.charAt(i-1)));  
	            }  
	              
	        }  
	        if (totalNumber >= 0 && totalNumber < 9) {  
	            return (10 - totalNumber);  
	        }else {  
	            String str = String.valueOf(totalNumber);  
	            if (Integer.parseInt(String.valueOf(str.charAt(str.length()-1))) == 0) {  
	                return 0;   
	            }else {  
	                return (10 - Integer.parseInt(String.valueOf(str.charAt(str.length()-1))));  
	            }  
	        }  
	          
	    }  
	      
	    /**  
	     * 计算数字各位和  
	     * @param number  
	     * @return  
	     */  
	    public static int calculate(int number){  
	        String str = String.valueOf(number);  
	        int total = 0;  
	        for (int i = 0; i < str.length(); i++) {  
	            total += Integer.valueOf(Integer.parseInt(String.valueOf(str.charAt(i))));  
	        }  
	        return total;  
	    }  

	  
	  public static void main(String arg[]){
		   //String cardNumber = "621785360000165466"; 
		   //String cardNumber = "622521190367959"; 
		   String cardNumber = "622700422667015732"; 
		   
		   System.out.println(getCheckNumber(cardNumber));  

		   
		   
	  }
	}

 

 

你可能感兴趣的:(JavaUtil)