131. Text to Number

A form reads numbers typed as free text. The string s is converted with these steps: skip all leading spaces; then optionally read one sign character, + or -; then read digits until the first character that is not a digit or the end of the text. The digits give the magnitude, and the sign decides the direction. If no digit is read, the result is 0.

The result must fit a signed 32-bit integer: values below -2147483648 become -2147483648 and values above 2147483647 become 2147483647. Return the converted number. Texts can be very long, so stop reading digits as soon as the value is certain to overflow.

Example 1

Input:
s = " +77 apples"
Output:
77
Explanation:

After the spaces and the plus sign the digits 77 are read; the space ends the number, so the result is 77.

Example 2

Input:
s = "-99999999999"
Output:
-2147483648
Explanation:

The value is far below the smallest 32-bit integer, so it is clamped to -2147483648.

Constraints

1 ≤ s.length ≤ 500000

s contains printable ASCII characters, including spaces

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…