Read a quantity someone typed
A stock adjustment screen takes a quantity as free text, and the parser refuses anything it cannot trust.
- Whitespace around the number is fine and is ignored.
- Only digits are allowed — no sign, no decimal point, no spaces inside.
- The value must be between 1 and 999.
- Anything else gives -1.
validQuantity(text: string) → int
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 validQuantity(text string) int {
}
Worked examples
| Call | Result |
|---|---|
validQuantity("5") | 5 |
validQuantity(" 12 ") | 12 |
validQuantity("999") | 999 |
validQuantity("0") | -1 |
Hint
Trim, reject an empty result, then check every remaining character before you convert.
Reference solution in Go
func validQuantity(text string) int {
t := strings.TrimSpace(text)
if t == "" {
return -1
}
for i := 0; i < len(t); i++ {
if t[i] < '0' || t[i] > '9' {
return -1
}
}
n, err := strconv.Atoi(t)
if err != nil || n < 1 || n > 999 {
return -1
}
return n
}