JAVA實現Luhn算法

JAVA實現Luhn算法

圖片.png
import java.util.Scanner;

class BigNum{
    
    int []num;  //位數
     
    public BigNum(){
        num = new int[21];
        for(int i = 0; i < num.length; i++) {
            num[i] = 0;
        }
    }
    
    public BigNum(int n) {
        num = new int[n];
    }
    public boolean full() {
        for(int i = 0; i < num.length; i++) {
            if(num[i] != 9) {
                return false;
            }
        }
        return true;
    }
     
    public void plusOne() {
        int tag = 0;    //從最后一位開始加,如果其9,將其變為0,另高一位加一,
                        //如果高一位是9,其變為0,高一位加一一次類推直到全為9
                        //tag == 0說明從第0位開始
        if(num[tag]!=9) {
            num[tag]++;
            return;
        }else {
            if(full())  return; //如果全為9則溢出
             
            //關鍵算法。。進位操作
            while(true) {
                num[tag]=0;
                tag++;
                if(num[tag] != 9) {
                    num[tag]++;
                    return;
                }
            }
        }
    }
    public void show() {
        for(int i = num.length-1; i >-1; i--) {
            System.out.print(num[i]);
        }
        System.out.println();
    }
    
    
    
    public void setElem(int pos, int n) {
        num[pos] = n;
    }
     
    public boolean isLuhn() {
        int OddPlus=0;  //奇數位和,在數組中為偶數位和
        int EvenPlus=0; //偶數位和,在數組中為奇數位和
        
        for(int i = 0; i < num.length; i+=2) {
            OddPlus+=num[i];
        }
        
        int num2=-999;
        for(int i = 1; i < num.length; i+=2) {
            num2 = num[i]*2;
            if (num2>9) {
                num2-=9;
            }
            EvenPlus+=num2;
        }
        OddPlus+=EvenPlus;
        if (OddPlus%10==0) {
            return true;
        }
        return false;
    }
}


public class ComformCreditCard {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System.in);
        
        //輸入字符串
        String str = scanner.next();
        //從字符串提取數字
        BigNum bNum = new BigNum(str.length());
        
        
        
        //放入數據
        for (int j = 0; j < str.length(); j++) {
            bNum.setElem(j, str.charAt(j)-48);
        }
        
        if (bNum.isLuhn()) {
            System.out.print("成功");
        }else {
            System.out.print("失敗");
        }
        
        
        
        
    }

}

運行結果

圖片.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。