Google
 
Web unafbapune.blogspot.com

Thursday, November 24, 2011

 

Yet another Luhn check and digit generation

But this time it's faster:

/**
* @param s non-empty string that contains only digits
* @return true only if the given digits pass the luhn check
*/
boolean isLuhn(String s) {
char[] ca = s.toCharArray();
int sum = ca[ca.length-1] - '0';

for (int i=ca.length-2; i >= 0; i-=2) {
int x2 = (ca[i] - '0') << 1;
sum += x2 < 10 ? x2 : 1 + (x2 - 10);
}
for (int i=ca.length-3; i >= 0; i-=2)
sum += ca[i] - '0';
return sum % 10 == 0;
}

/**
* @param s non-empty string that contains only digits
* @return the generated Luhn digit
*/
int calculateLuhnDigit(String s) {
char[] ca = s.toCharArray();
int sum = 0;

for (int i=ca.length-1; i >= 0; i-=2) {
int x2 = (ca[i] - '0') << 1;
sum += x2 < 10 ? x2 : 1 + (x2 - 10);
}
for (int i=ca.length-2; i >= 0; i-=2)
sum += ca[i] - '0';
int mod = sum % 10;
return mod == 0 ? 0 : 10 - mod;
}

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?