FastPrepString to Integer (atoi)

String to Integer (atoi)

Apple logoApple● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Convert the leading decimal integer in the ASCII string text into a signed 32-bit integer.

  1. Skip leading ASCII whitespace: space, tab, line feed, vertical tab, form feed, or carriage return.
  2. Read at most one optional + or - sign.
  3. Read the immediately following consecutive digits. Stop at the first nondigit; ignore the remaining suffix.
  4. Return zero if no digits were read. Clamp a value outside [-2147483648,2147483647] to the nearest endpoint.

Only the leading digit run is parsed; decimal points, exponents, and later digit runs are not special syntax.

Function

parseAtoi(text: String) → int

Examples

Example 1

text = "   -42tail"return = -42

Skip spaces, read the minus sign and digits 42, and stop before the suffix.

Example 2

text = "4193 with words"return = 4193

Parsing stops at the first space after the digits.

Example 3

text = "words 987"return = 0

The leading non-whitespace character is not a sign or digit.

Constraints

  • 0 <= text.length <= 2000.
  • Every input character is ASCII.

More Apple problems

See Apple hiring insights
public int parseAtoi(String text) {
    // Write your solution here.
}
text" -42tail"
expected-42
Checking account…