信用卡校验位算法THE LUHN MOD-10
程序员文章站
2022-07-14 19:04:48
...
信用卡校验位算法THE LUHN MOD-10 http://blogread.cn/it/article/6324?f=wb
import org.apache.commons.lang3.StringUtils; public class CreditCardValidator { /** * 1. 对卡号上的每位数字乘以权重。其规则是,如果卡号数字个数是偶数,则第一位乘以2,否则就乘以1,然后以后分别是,1,2,1,2,1,2; * * 2. 如果每位数字乘以权重后超过9 ,则需要减去 9; * * 3. 将所有的处理过的加权数字求和,用 数字 10 求模运算; * * 4. 余数应该是0,否则可能是输入错误。也可能是一个假号。 * * @param cardNo * @return */ public static boolean isValid(String cardNo) { if (StringUtils.isBlank(cardNo) || !StringUtils.isNumeric(cardNo)) return false; int len = cardNo.length(); boolean isOdd = len % 2 == 1; int total = 0; int tem = 0; for (int i = 0; i < len; i++) { tem = Integer.valueOf(String.valueOf(cardNo.charAt(i))); if (i == 0 && !isOdd) { tem = tem << 1; } else if (i > 0 && i % 2 == 0) { tem = tem << 1; } if (tem > 9) tem = tem - 9; total = total + tem; } return total % 10 == 0; } }
上一篇: Singleton design pattern in java
下一篇: 转:ajax乱码解决汇总