String to Integer (atoi)
Real-world version: Salvage the Leading NumberThe statement here is our own: the same inputs, outputs and technique.
A telemetry importer receives one text field per row and has to salvage a whole number from the front of it. Implement the salvage routine, which behaves like this:
- Step over every space character sitting at the very front of
field. - If the character now under the cursor is
+or-, consume that one character and let it decide the sign. Only the first such character counts; a second one is not part of a number. - Consume the run of decimal digits that follows, stopping at the first character that is not a digit or at the end of the field. Leading zeros are harmless. Everything from the stopping point onward, whatever it is, is discarded.
- If step 3 consumed no digits at all, the salvaged value is
0. - The importer stores the result in a 32-bit signed register whose range is
-2147483648through2147483647inclusive. A salvaged value below that range is reported as-2147483648, and a value above it as2147483647.
Return the value the importer stores. Do not treat any character other than a space as padding.
Examples
Example 1
- Input
- field = " -0073abc"
- Output
- -73
Two spaces are stepped over, the minus fixes the sign, then 0073 is consumed and abc is discarded.
Example 2
- Input
- field = "8x7"
- Output
- 8
The digit run ends at x, so the trailing 7 never gets looked at.
Example 3
- Input
- field = ".55"
- Output
- 0
A period is neither a space nor a sign nor a digit, so the cursor stops before any digit is consumed.
Example 4
- Input
- field = "-99999999999"
- Output
- -2147483648
The salvaged value sits below the register floor and is reported as the floor.
Constraints
- 0 <= field.length <= 200
- field contains only English letters (upper and lower case), digits, ' ', '+', '-' and '.'
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def salvage_number(field: str) -> int:public int salvageNumber(String field)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 4 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's