本文主要是介绍Luhn验证银行卡号是否合法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package com.dcqq.common.utils;public class LuhnUtil {public static void main(String[] args) {boolean b = checkBankCardId("62290860202331251");System.out.println(b);}/*** 检验银行卡号是否合法* 采用Luhn算法检验* 校验算法步骤:* 1、从卡号最后一位数字开始,逆向将奇数位(1、3、5等等)相加。* 2、从卡号最后一位数字开始,逆向将偶数位数字乘以2(如果乘积为两位数,则将其减去9),再求和。* 3、将奇数位总和加上偶数位总和,结果应该可以被10整除。* @param bankCardId 银行卡号* @return true合法;false不合法*/public static boolean checkBankCardId(String bankCardId){if (bankCardId == null)return false;int length = bankCardId.length();if (length < 15 || length > 19)return false;int total = 0;for (int i = 0; i < length; i++) {char c = bankCardId.charAt(length - 1 - i);int valueOfChar = Character.getNumericValue(c);if ((i + 1) % 2 == 0) {//偶数位int temp = valueOfChar * 2;temp = temp / 10 + temp % 10;
// temp = temp > 9 ? temp - 9 : temp;total = total + temp;} else {total = total + valueOfChar;}}return total % 10 == 0;}}
参考:https://blog.csdn.net/weixin_30438813/article/details/97993666?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2defaultBlogCommendFromBaiduRate-5-97993666-blog-126628470.235%5Ev43%5Epc_blog_bottom_relevance_base3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2defaultBlogCommendFromBaiduRate-5-97993666-blog-126628470.235%5Ev43%5Epc_blog_bottom_relevance_base3&utm_relevant_index=10
https://blog.csdn.net/jshch2009/article/details/55255236?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-2-55255236-blog-97993666.235%5Ev43%5Epc_blog_bottom_relevance_base3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-2-55255236-blog-97993666.235%5Ev43%5Epc_blog_bottom_relevance_base3&utm_relevant_index=3
这篇关于Luhn验证银行卡号是否合法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!