20 · String Parsing & Expression Evaluation

#8 String to Integer (atoi)

Mediumsolve on LeetCode ↗

frequently reported atNetflixBloombergMetaAmazonMicrosoftGoogle

the problem

In plain words

Turn a string into a 32-bit signed int, the way C's atoi reads text. First skip any spaces at the start. Then read at most one '+' or '-' (no sign means positive). Then read digits until a character that isn't a digit, or the end. Leading zeros are fine. If no digits were read, the answer is 0. If the number is outside [−2³¹, 2³¹ − 1], return the nearest end of that range.

in s = "42"

out 42

in s = " -042"

out -42

Spaces skipped, '-' read, then 042 = 42.

in s = "1337c0d3"

out 1337

Reading stops at 'c'.

in s = "0-1"

out 0

After the 0, '-' is not a digit, so reading stops.

in s = "words and 987"

out 0

A letter comes before any digit.

  • 0 ≤ s.length ≤ 200
  • s has English letters, digits, ' ', '+', '-' and '.'

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #7
      Reverse Integer
      Mediumin Math & Numbers
    2. #227
      Basic Calculator II
      Mediumin Parsing
    3. #13
      Roman to Integer
      Easyin Parsing