Created
September 26, 2021 15:52
-
-
Save deepumi/57a3448515b9ec7bd39122ebbd392cff to your computer and use it in GitHub Desktop.
The Luhn Algorithm in C#
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
private static bool PassesLuhnTest(string cardNumber) | |
{ | |
ReadOnlySpan<char> value = cardNumber; | |
var sum = 0; | |
var isDouble = false; | |
for (var i = value.Length - 1; i >= 0; i--) | |
{ | |
int digit; | |
if (value[i] >= 48 && value[i] <= 57) | |
{ | |
digit = value[i] - '0'; | |
if (isDouble && (digit *= 2) > 9) | |
{ | |
digit -= 9; | |
} | |
sum += digit; | |
isDouble = !isDouble; | |
} | |
} | |
return sum % 10 == 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment