oneby7

Strings Parsing and conversion

138. String to Integer (atoi)

Medium

You are given a string s. Read a whole number from the start of s, the way the C function atoi does, and return it as a signed 32-bit integer. Read s from left to right in this order:

  1. Skip the spaces at the start of s.
  2. If the next character is + or -, it is the sign of the number. Without a sign, the number is positive.
  3. Read digits until a character that is not a digit, or the end of s. Zeros at the front of the number add nothing to it.

Everything after the digits is ignored, even more digits after a space. If no digit is read, the answer is 0.

A signed 32-bit integer holds the values from −231 to 231 − 1, that is from −2,147,483,648 to 2,147,483,647. If the number is larger than 2,147,483,647, return 2,147,483,647. If it is smaller than −2,147,483,648, return −2,147,483,648.

Interviewers often ask for this problem to be solved with 32-bit integers only, as if no wider type existed. So no value in your code should go outside that range, even for a moment.

Example 1

Input: s = " -0071 apples"

Output: -71

Explanation: The spaces at the start are skipped, and the - makes the number negative. Then the digits 0071 are read up to the space after them. Zeros at the front add nothing, so the answer is −71.

Example 2

Input: s = "9876543210"

Output: 2147483647

Explanation: 9,876,543,210 is larger than 2,147,483,647, the largest 32-bit value, so the answer is 2,147,483,647.

Example 3

Input: s = "page 42"

Output: 0

Explanation: The first character is p. It is not a space, a sign or a digit, so no digit is read and the answer is 0.

Check your understanding

Work out the answer for this input before you write any code.

s = " -2147483649x"

Constraints

  • 0 ≤ s.length ≤ 105
  • s holds only English letters (lowercase and uppercase), digits, spaces ' ', '+', '-' and '.'

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.