Strings Parsing and conversion
138. String to Integer (atoi)
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:
- Skip the spaces at the start of
s. - If the next character is
+or-, it is the sign of the number. Without a sign, the number is positive. - 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"
-71Explanation: 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"
2147483647Explanation: 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"
0Explanation: 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.
Constraints
0 ≤ s.length ≤ 105sholds only English letters (lowercase and uppercase), digits, spaces' ','+','-'and'.'
Clarifying questions
What you would ask an interviewer before writing any code.