Applied AI Engineer (LLM) coding learning path Level 2 This level · 13 of 31

String to Integer (atoi)

Medium Parsing

Problem

Implement the conversion of a string to a 32-bit signed integer, following the usual atoi rules: leading whitespace, an optional sign, a run of digits, then clamp the result into the range from -2³¹ to 2³¹-1.

Original: LeetCode 8: String to Integer (atoi).

Examples

Example 1

Input`s = "42"`
Output`42`

Example 2

Input`s = " -42"`
Output`-42`

Example 3

Input`s = "1337c0d3"`
Output`1337`

Example 4

Input`s = "0-1"`
Output`0`

Example 5

Input`s = "words and 987"`
Output`0`

Example 6

Input`s = "2147483648"`
Output`2147483647`

Example 7

Input`s = "-2147483649"`
Output`-2147483648`

Constraints

  • 0 <= s.length <= 200
  • s consists of English letters (lower-case and upper-case), digits (0 - 9), ' ', '+', '-', and '.'.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 8: String to Integer (atoi)leetcode.com
  2. Java SE 17 API: Integer.MAX_VALUEdocs.oracle.com
Previous
Next