Drill

ProblemsC++ › validation

Verify a barcode

mediumvalidationStringsMathC++

A scanner sometimes misreads a digit. The EAN-13 check digit catches most of those before the wrong product reaches the basket.

barcodeValid(code: 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

bool barcodeValid(std::string code) {
    
}

Worked examples

CallResult
barcodeValid(std::string("4006381333931"))true
barcodeValid(std::string("4006381333932"))false
barcodeValid(std::string("400638133393"))false
barcodeValid(std::string("400638133393a"))false

Hint

The check digit is the thirteenth and takes part in the sum like any other.

Reference solution in C++
bool barcodeValid(std::string code) {
    if (code.size() != 13) return false;
    int sum = 0;
    for (int i = 0; i < 13; i++) {
        char c = code[i];
        if (c < '0' || c > '9') return false;
        int d = c - '0';
        sum += (i % 2 == 0) ? d : d * 3;
    }
    return sum % 10 == 0;
}

The same problem in another language

More validation problems in C++