Last active
April 4, 2017 09:22
-
-
Save HussainDerry/660a7475308f8e0f2d50fc8df887020e to your computer and use it in GitHub Desktop.
Helper class to check the validity of card numbers using the Luhn algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * A helper class to check number validity using the Luhn algorithm. | |
| * @author Hussain Al-Derry <[email protected]> | |
| */ | |
| public class LuhnChecker { | |
| /** | |
| * Checks number's validity using the last digit as a check digit. | |
| * @param number The number to check | |
| * @return boolean whether the number is valid or not. | |
| * */ | |
| public static boolean checkNumberValidity(String number){ | |
| int[] numbers = stringToIntArray(number); | |
| int finalDigit = numbers[numbers.length - 1]; | |
| for(int j = numbers.length - 2; j >= 0; j-=2){ | |
| numbers[j] *= 2; | |
| if(numbers[j] > 9){ | |
| numbers[j] -= 9; | |
| } | |
| } | |
| int totalSum = 0; | |
| for(int n = 0; n < numbers.length - 1; n++){ | |
| totalSum += numbers[n]; | |
| } | |
| return ((totalSum * 9) % 10) == finalDigit; | |
| } | |
| private static int[] stringToIntArray(String str){ | |
| int[] numbers = new int[str.length()]; | |
| for(int i = str.length() - 1; i >= 0; i--) { | |
| numbers[i] = Integer.parseInt(str.substring(i, i + 1)); | |
| } | |
| return numbers; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment