Check Credit Card Validity using Luhn Algorithm

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

    There are two ways to split up your int into List

    1. Use %10 as you are using and store it into a List
    2. Convert to a String and then take the numeric values

    Here are a couple of quick examples

    public static void main(String[] args) throws Exception {
        final int num = 12345;
        final List nums1 = splitInt(num);
        final List nums2 = splitString(num);
        System.out.println(nums1);
        System.out.println(nums2);
    }
    
    private static List splitInt(int num) {
        final List ints = new ArrayList<>();
        while (num > 0) {
            ints.add(0, num % 10);
            num /= 10;
        }
        return ints;
    }
    
    private static List splitString(int num) {
        final List ints = new ArrayList<>();
        for (final char c : Integer.toString(num).toCharArray()) {
            ints.add(Character.getNumericValue(c));
        }
        return ints;
    }
    

提交回复
热议问题