Skip to content

Instantly share code, notes, and snippets.

@deepumi
Created September 26, 2021 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepumi/57a3448515b9ec7bd39122ebbd392cff to your computer and use it in GitHub Desktop.
Save deepumi/57a3448515b9ec7bd39122ebbd392cff to your computer and use it in GitHub Desktop.
The Luhn Algorithm in C#
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