Check Credit Card Validity using Luhn Algorithm

前端 未结 12 1564
刺人心
刺人心 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:20

    I'll use 5 digit card numbers for simplicity. Let's say your card number is 12345; if I read the code correctly, you store in array the individual digits:

    array[] = {1, 2, 3, 4, 5}
    

    Since you already have the digits, in sumOfOddPlace you should do something like

    public static int sumOfOddPlace(long[] array) {
        int result = 0;
        for (int i = 1; i < array.length; i += 2) {
            result += array[i];
        }
        return result;
    }
    

    And in sumOfDoubleEvenPlace:

    public static int sumOfDoubleEvenPlace(long[] array) {
        int result = 0;
        for (int i = 0; i < array.length; i += 2) {
            result += getDigit(2 * array[i]);
        }
        return result;
    }
    

提交回复
热议问题