All problems
0092MediumString

Salvage the Leading Number

Tracked in this browser only
Write code

Trains the technique from

LeetCode 8String to Integer (atoi)

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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:

  1. Step over every space character sitting at the very front of field.
  2. 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.
  3. 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.
  4. If step 3 consumed no digits at all, the salvaged value is 0.
  5. The importer stores the result in a 32-bit signed register whose range is -2147483648 through 2147483647 inclusive. A salvaged value below that range is reported as -2147483648, and a value above it as 2147483647.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def salvage_number(field: str) -> int:
Java
public int salvageNumber(String field)
September 7
Apply