Show problems as
Classic problem #8MediumString

String to Integer (atoi)

Real-world version: Salvage the Leading Number
Tracked in this browser only
Read String to Integer (atoi) on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstString Manipulation · Strings, animated step by step

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

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