This is pretty simple, you just need to implement the algorithm.
static Integer accumulate(String[] digits, Boolean validate) {
// This algorithm goes from the *left*, so we need to know which to double
Integer checkSize = validate? 1: 0;
Integer accumulator = 0;
while(!digits.isEmpty()) {
Integer nextDigit = Integer.valueOf(digits.remove(0));
// We should double the value when true
if((digits.size()&1) == checkSize) {
nextDigit <<= 1;
// And "add together" the individual digits when 10+
if(nextDigit > 9) {
nextDigit -= 9;
}
}
accumulator += nextDigit;
}
return accumulator;
}
// Returns true if the valid Luhn check digit present
public static Boolean validateLuhnCheckDigit(String source) {
return 0 == Math.mod(accumulate(source.split(''), true), 10);
}
// Returns the check digit for a given string
public static String calculateLuhnCheckDigit(String source) {
return ''+Math.mod(accumulate(source.split(''), false) * 9, 10);
}
No error checking is provided, and is left as an exercise to the reader.
String donorId = '0115839'; Integer sum = 0; Integer len = donorId.length(); for(Integer i=len-1;i>=0;i--){ Integer num = Integer.ValueOf(donorId.substring(i,i+1)); if ( math.mod(i , 2) == math.mod(len, 2) ) { Integer n = num * 2; sum += (n / 10) + ( math.mod(n, 10)); System.debug('Output1: ' + sum); String result = donorId + sum; System.debug('CRN: ' + result); } else{ sum += num; System.debug('Output2: ' + sum); } }