luhn algorithm java_luhn校验算法(Java实现)

Luhn算法,又称Luhn公式,是一种简单的校验和公式,用于验证信用卡号、IMEI号等识别号。本文介绍了算法原理,并提供了一个Java实现的示例,演示如何检查输入的信用卡号码是否通过Luhn校验。
摘要由CSDN通过智能技术生成

TheLuhn algorithmorLuhn formula, also known as the "modulus10" or "mod 10"algorithm, is a simplechecksumformula used to validate a variety of identification numbers, such ascredit card numbers,IMEI numbers,National Provider Identifier numbersin US andCanadianSocial Insurance Numbers. It was created byIBMscientistHans Peter Luhnand described inU.S. Patent No. 2,950,048, filed on January 6, 1954, and granted on August 23, 1960.——来自维基百科(http://en.wikipedia.org/wiki/Luhn_algorithm)。

案例

当你输入信用卡号码的时候,有没有担心输错了而造成损失呢?其实可以不必这么担心,因为并不是一个随便的信用卡号码都是合法的,它必须通过Luhn算法来验证通过。

该校验的过程:

1、从卡号最后一位数字开始,逆向将奇数位(1、3、5等等)相加。

2、从卡号最后一位数字开始,逆向将偶数位数字,先乘以2(如果乘积为两位数,则将其减去9),再求和。

3、将奇数位总和加上偶数位总和,结果应该可以被10整除。

例如,卡号是:5432123456788881

则奇数、偶数位(用红色标出)分布:5432123456788881

奇数位和=35

偶数位乘以2(有些要减去9)的结果:16 2 6 1 5 7 7,求和=35。

最后35+35=70可以被10整除,认定校验通过。

import java.util.Scanner;

//信用卡号校验算法

public class Luhn {

public static void main(String[] args) {

System.out.println("Please input your credit card number:");

Scanner input = new Scanner(System.in);

int sumOdd = 0;

int sumEven = 0;

String number = input.next();

int length = number.length();

int[] wei = new int[length];

for (int i = 0; i < number.length(); i++) {

wei[i] = Integer.parseInt(number.substring(length - i - 1, length

- i));// 从最末一位开始提取,每一位上的数值

System.out.println("第" + i + "位数字是:" + wei[i]);

}

for (int i = 0; i < length / 2; i++) {

sumOdd += wei[2 * i];

if ((wei[2 * i + 1] * 2) > 9)

wei[2 * i + 1] = wei[2 * i + 1] * 2 - 9;

else

wei[2 * i + 1] *= 2;

sumEven += wei[2 * i + 1];

}

System.out.println("奇数位的和是:" + sumOdd);

System.out.println("偶数位的和是:" + sumEven);

if ((sumOdd + sumEven) % 10 == 0)

System.out.println("Recept.");

else

System.out.println("Can not recept.");

}

}

运行结果:

Please input your credit card number: 5432123456788881 第0位数字是:1 第1位数字是:8 第2位数字是:8 第3位数字是:8 第4位数字是:8 第5位数字是:7 第6位数字是:6 第7位数字是:5 第8位数字是:4 第9位数字是:3 第10位数字是:2 第11位数字是:1 第12位数字是:2 第13位数字是:3 第14位数字是:4 第15位数字是:5 奇数位的和是:35 偶数位的和是:35 Recept.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值