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
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.
Where you start
public int ValidQuantity(string text) {
}
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 C#
public int ValidQuantity(string text) {
string t = text.Trim();
if (t.Length == 0) return -1;
foreach (char c in t) if (c < '0' || c > '9') return -1;
long n = long.Parse(t);
return (n >= 1 && n <= 999) ? (int) n : -1;
}