http://stackoverflow.com/questions/26383926/luhn-algorithm-java
1 static boolean luhn(String pnr){
2 // this only works if you are certain all input will be at least 10 characters
3 int extraChars = pnr.length() - 10;
4 if (extraChars < 0) {
5 throw new IllegalArgumentException("Number length must be at least 10 characters!");
6 }
7 pnr = pnr.substring(extraChars, 10 + extraChars);
8 int sum = 0;
9 for (int i = 0; i < pnr.length(); i++){
10 char tmp = pnr.charAt(i);
11 int num = tmp - '0';
12 int product;
13 if (i % 2 != 0){
14 product = num * 1;
15 }
16 else{
17 product = num * 2;
18 }
19 if (product > 9)
20 product -= 9;
21 sum+= product;
22 }
23 return (sum % 10 == 0);
24 }
25
26 private static void printMessage(boolean valid) {
27 if (valid){
28 System.out.print("Valid!
");
29 }
30 else{
31 System.out.print("Invalid!");
32 }
33 }
34 }
static private boolean checkDeviceIDVal(String deviceid)
{
if(deviceid == null)
{
Log.e(TAG, "device id is null");
return false;
}
else
{
int s1 = 0, s2 = 0;
String reverse = new StringBuffer(deviceid).reverse().toString();
for(int i = 0 ;i < reverse.length();i++)
{
int digit = Character.digit(reverse.charAt(i), 10);
if(i % 2 == 0)
{
//this is for odd digits, they are 1-indexed in the algorithm
s1 += digit;
}
else
{
//add 2 * digit for 0-4, add 2 * digit - 9 for 5-9
s2 += 2 * digit;
if(digit >= 5)
{
s2 -= 9;
}
}
}
return (s1 + s2) % 10 == 0;
}
}