JAVA實(shí)現(xiàn)Luhn算法

圖片.png
import java.util.Scanner;
class BigNum{
int []num; //位數(shù)
public BigNum(){
num = new int[21];
for(int i = 0; i < num.length; i++) {
num[i] = 0;
}
}
public BigNum(int n) {
num = new int[n];
}
public boolean full() {
for(int i = 0; i < num.length; i++) {
if(num[i] != 9) {
return false;
}
}
return true;
}
public void plusOne() {
int tag = 0; //從最后一位開始加,如果其9,將其變?yōu)?,另高一位加一,
//如果高一位是9,其變?yōu)?,高一位加一一次類推直到全為9
//tag == 0說(shuō)明從第0位開始
if(num[tag]!=9) {
num[tag]++;
return;
}else {
if(full()) return; //如果全為9則溢出
//關(guān)鍵算法。。進(jìn)位操作
while(true) {
num[tag]=0;
tag++;
if(num[tag] != 9) {
num[tag]++;
return;
}
}
}
}
public void show() {
for(int i = num.length-1; i >-1; i--) {
System.out.print(num[i]);
}
System.out.println();
}
public void setElem(int pos, int n) {
num[pos] = n;
}
public boolean isLuhn() {
int OddPlus=0; //奇數(shù)位和,在數(shù)組中為偶數(shù)位和
int EvenPlus=0; //偶數(shù)位和,在數(shù)組中為奇數(shù)位和
for(int i = 0; i < num.length; i+=2) {
OddPlus+=num[i];
}
int num2=-999;
for(int i = 1; i < num.length; i+=2) {
num2 = num[i]*2;
if (num2>9) {
num2-=9;
}
EvenPlus+=num2;
}
OddPlus+=EvenPlus;
if (OddPlus%10==0) {
return true;
}
return false;
}
}
public class ComformCreditCard {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
//輸入字符串
String str = scanner.next();
//從字符串提取數(shù)字
BigNum bNum = new BigNum(str.length());
//放入數(shù)據(jù)
for (int j = 0; j < str.length(); j++) {
bNum.setElem(j, str.charAt(j)-48);
}
if (bNum.isLuhn()) {
System.out.print("成功");
}else {
System.out.print("失敗");
}
}
}
運(yùn)行結(jié)果

圖片.png