package com.heyu.api.data.utils;

public class BankCardUtils {
    /**
     * 使用Luhn算法校验银行卡号是否有效
     *
     * @param cardNumber 要校验的银行卡号字符串
     * @return 如果银行卡号有效返回true，否则返回false
     */
    public static boolean isValidBankCard(String cardNumber) {
        if (cardNumber == null || !cardNumber.matches("\\d+")) {
            return false;
        }

        int sum = 0;
        boolean alternate = false;
        for (int i = cardNumber.length() - 1; i >= 0; i--) {
            int n = Integer.parseInt(cardNumber.substring(i, i + 1));
            if (alternate) {
                n *= 2;
                if (n > 9) {
                    n = (n % 10) + 1; // 或者 n = (n / 10) + (n % 10);
                }
            }
            sum += n;
            alternate = !alternate;
        }

        return (sum % 10 == 0);
    }
}
