package com.example.modifier;

import org.junit.Test;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

public class Luhn {
    private static char[] CHECKS = "0987654321".toCharArray();

    public static boolean isValidLuhn(String number) {

        if (number == null) {
            return false;
        }

        char[] chs = number.toCharArray();
        int count = 0;

        for (int i = chs.length - 2, k = 1; i >= 0; i--, k++) {

            // 不是数字字符时直接返回 false
            if (chs[i] < '0' || chs[i] > '9') {
                return false;
            }

            // 偶位数字 * 2，奇位不乘
            int num = (chs[i] - '0') << (k & 1);

            // 累加
            count += num % 10 + num / 10;
        }

        System.out.println(CHECKS[count % 10]);
        // 对校验位进行比对
        return (chs[chs.length - 1] == CHECKS[count % 10]);
    }

    @Test
    public void test() {
        assert isValidLuhn("89660166219355995276");

    }
}
