Verify a barcode
A scanner sometimes misreads a digit. The EAN-13 check digit catches most of those before the wrong product reaches the basket.
- The code is exactly thirteen digits.
- Counting from one, digits in odd positions count once and digits in even positions count three times.
- The code is valid when that total divides by ten.
- Anything not thirteen digits long, or containing a non-digit, is invalid.
barcodeValid(code: string) → bool
Go 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.
Where you start
func barcodeValid(code string) bool {
}
Worked examples
| Call | Result |
|---|---|
barcodeValid("4006381333931") | true |
barcodeValid("4006381333932") | false |
barcodeValid("400638133393") | false |
barcodeValid("400638133393a") | false |
Hint
The check digit is the thirteenth and takes part in the sum like any other.
Reference solution in Go
func barcodeValid(code string) bool {
if len(code) != 13 {
return false
}
sum := 0
for i := 0; i < 13; i++ {
c := code[i]
if c < '0' || c > '9' {
return false
}
d := int(c - '0')
if i%2 == 0 {
sum += d
} else {
sum += d * 3
}
}
return sum%10 == 0
}