Drill

ProblemsC# › payments

Luhn check a card number

mediumpaymentsStringsMathC#

Before a card ever reaches the payment gateway, the checkout runs the Luhn checksum so an obvious typo is caught in the browser.

LuhnValid(digits: string) → bool

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public bool LuhnValid(string digits) {
    
}

Worked examples

CallResult
LuhnValid("79927398713")true
LuhnValid("79927398710")false
LuhnValid("4111 1111 1111 1111")true
LuhnValid("4111-1111-1111-1112")false

Hint

Strip the formatting into a clean string first. Then walk it backwards with an index so "every second" is easy to say.

Reference solution in C#
public bool LuhnValid(string digits) {
    var clean = new StringBuilder();
    foreach (char c in digits) {
        if (c == ' ' || c == '-') continue;
        if (c < '0' || c > '9') return false;
        clean.Append(c);
    }
    if (clean.Length < 2) return false;
    int sum = 0;
    for (int i = 0; i < clean.Length; i++) {
        int d = clean[clean.Length - 1 - i] - '0';
        if (i % 2 == 1) { d *= 2; if (d > 9) d -= 9; }
        sum += d;
    }
    return sum % 10 == 0;
}

The same problem in another language

More payments problems in C#