Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can produce wrong result #3

Open
clayjh opened this issue Aug 5, 2019 · 2 comments
Open

Can produce wrong result #3

clayjh opened this issue Aug 5, 2019 · 2 comments

Comments

@clayjh
Copy link

clayjh commented Aug 5, 2019

The luhn algorithm has to start from the furthest right of the card number. I would reverse the string before you set n

@eix128
Copy link
Owner

eix128 commented Sep 20, 2020

Try this :

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");
}

}
}

@eix128
Copy link
Owner

eix128 commented Sep 20, 2020

Or try this:

public static boolean checkCreditCard(String cc) {
final boolean[] dbl = {false};
return cc
.replaceAll("\s+", "")
.chars()
.map(c -> Character.digit((char) c, 10))
.map(i -> ((dbl[0] = !dbl[0])) ? (((i2)>9) ? (i2)-9 : i*2) : i)
.sum() % 10 == 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants