2

I have the following code for validating IMEIs (not SV)

public static boolean luhnc(char[] digits) {
    int sum = 0, s = 0;
    for (int i = 0; i < digits.length - 1; i += 2) {
        s = (digits[i+1] - '0') * 2;
        sum += (s > 10 ? s - 9 : s) + (digits[i] - '0');
    }
    return 10 - (sum % 10) == (digits[digits.length-1] - '0');
}

Almost every IMEI checks out except for my Samsung Galaxy Note 4.

I do not want to post it here for obvious reasons but at the same time I need someone to verify that it works.

Perhaps it's my implementation that's not right.

Please help.

Volo
  • 28,673
  • 12
  • 97
  • 125
TheRealChx101
  • 1,468
  • 21
  • 38

2 Answers2

1

There is a point you miss in Luhn algo after do the *2 operation, it's

  • if the number is >=10 (and not >), because 10 becomes 0 instead of 1

So fix like this (I extract it in a new line to be clear for you) :

for (int i = 0; i < digits.length - 1; i += 2) {
    s = (digits[i + 1] - '0') * 2;                 
    sum += (s >= 10 ? s - 9 : s) + (digits[i] - '0');
}

Also I would recommand to use a int[] instead of char[] to remove the - '0' everywhere

azro
  • 53,056
  • 7
  • 34
  • 70
  • Ah. Thanks. So it's *>=* and not *>*. It validates now. Thanks. Also, conversely, we can subtract 9 to get the same result of adding the two digits of the greater number. :) – TheRealChx101 Sep 09 '17 at 15:27
  • @TheRealChx101 ha yes you're right, I never think about doing that way ^^ – azro Sep 09 '17 at 15:45
1

Another alternative is to use the library from Apache Commons.

org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(imei)

Jakg
  • 922
  • 12
  • 39