Check Credit Card Validity using Luhn Algorithm

前端 未结 12 1565
刺人心
刺人心 2020-12-03 04:02

I tried to check the validation of credit card using Luhn algorithm, which works as the following steps:

  1. Double every second digit from right to left. If do

12条回答
  •  伪装坚强ぢ
    2020-12-03 04:14

    this is the luhn algorithm implementation which I use for only 16 digit Credit Card Number

    if(ccnum.length()==16){
        char[] c = ccnum.toCharArray();
        int[] cint = new int[16];
        for(int i=0;i<16;i++){
            if(i%2==1){
                cint[i] = Integer.parseInt(String.valueOf(c[i]))*2;
                if(cint[i] >9)
                    cint[i]=1+cint[i]%10;
            }
            else
                cint[i] = Integer.parseInt(String.valueOf(c[i]));
        }
        int sum=0;
        for(int i=0;i<16;i++){
            sum+=cint[i];
        }
        if(sum%10==0)
            result.setText("Card is Valid");
        else
            result.setText("Card is Invalid");
    }else
        result.setText("Card is Invalid");
    

    If you want to make it use on any number replace all 16 with your input number length.

    It will work for Visa number given in the question.(I tested it)

提交回复
热议问题