luhn算法java
Recently I came to know that Credit Card numbers are not random and passes Luhn Algorithm test.
最近,我知道信用卡号不是随机的,并且通过了Luhn算法测试。
Java信用卡验证 (Java Credit Card Validation)
Any credit card number should pass following test:
任何信用卡号都应通过以下测试:
- From the rightmost digit, we should double every second digit. If the double is greater than 9, then add the both digits so that final number is of single digit. 从最右边的数字开始,我们应该每隔两位数字加倍。 如果双精度数大于9,则将两个数字相加,以使最终数字为一个数字。
- Now sum all the digits in the number, the unchanged numbers and the doubled numbers. 现在将数字中的所有数字,未更改的数字和加倍的数字相加。
- The final sum should be multiple of 10 or mod 10 of the number should be 0. If it’s not then its not a valid credit card number. 最终的总和应该是10的倍数,或者数字的mod 10应该是0。如果不是,则它不是有效的信用卡号。
Let’s check it with an example credit card number 12345678903555.
让我们用示例信用卡号12345678903555进行检查。
Digits are : 1,2,3,4,5,6,7,8,9,0,3,5,5,5
After doubling : 2,2,6,4,1,6,5,8,9,0,6,5,1,5
Sum of digits : 2+2+6+4+1+6+5+8+9+0+6+5+1+5 = 60 = 6*10 and hence a valid credit card number.
数字为:1,2,3,4,5,6,7,8,9,0,3,5,5,5
加倍后:2,2,6,4,1,6,5,8,9,0,6,5,1,5
数字总和:2 + 2 + 6 + 4 + 1 + 6 + 5 + 8 + 9 + 0 + 6 + 5 + 1 + 5 = 60 = 6 * 10,因此是有效的信用卡号。
Java中的Luhn算法 (Luhn Algorithm in Java)
Here I am providing java Luhn Algorithm program to validate credit card numbers.
在这里,我提供了Java Luhn算法程序来验证信用卡号。
package com.journaldev.util;
public class JavaLuhnAlgorithm {
public static void main(String[] args) {
validateCreditCardNumber("12345678903555");
String imei = "012850003580200";
validateCreditCardNumber(imei);
}
private static void validateCreditCardNumber(String str) {
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum += ints[i];
}
if (sum % 10 == 0) {
System.out.println(str + " is a valid credit card number");
} else {
System.out.println(str + " is an invalid credit card number");
}
}
}
Here I am taking input to the validation method as String, so that it will work also where the first digit is 0.
在这里,我将验证方法的输入作为String输入,以便在第一个数字为0的情况下也可以使用。
Output of the above program is:

上面程序的输出是:
12345678903555 is a valid credit card number
012850003580200 is a valid credit card number
Note that mobile phone IMEI number also follows the Luhn algorithm, go ahead and test it for your credit card numbers. 🙂
请注意,手机的IMEI号码也遵循Luhn算法,请继续进行测试以检查您的信用卡号。 🙂
翻译自: https://www.journaldev.com/1443/java-credit-card-validation-luhn-algorithm-java
luhn算法java