Drill

ProblemsGo › validation

Read a quantity someone typed

easyvalidationParsingStringsGo

A stock adjustment screen takes a quantity as free text, and the parser refuses anything it cannot trust.

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.

Solve it in Python →

Where you start

func validQuantity(text string) int {
	
}

Worked examples

CallResult
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
}

The same problem in another language

More validation problems in Go