v9.1.1
Menu

String to Integer (atoi)

mediumPROArrays & StringsMeta DSA

Implement myAtoi(s) which converts a string to a 32-bit signed integer:

  1. Skip leading whitespace
  2. Read an optional '+' or '-' sign
  3. Read digits until a non-digit character or end of string
  4. Clamp the result to the 32-bit signed integer range: [-2^31, 2^31 - 1]
  5. Return 0 if no digits were read

Example

Input
   -42
Output
-42
Reasoning
  • The function skips leading whitespace, but since there's none in the input -42, it proceeds to the next step.
  • It reads the optional sign, which is - in this case, indicating a negative number.
  • The function then reads the digits 42 and converts them to an integer: result=−1⋅42=−42result = -1 \cdot 42 = -42.
  • Since −42-42 is within the 32-bit signed integer range [−231,231−1][-2^{31}, 2^{31} - 1], the result is not clamped and is returned as is.
  • The final output is -42.

Constraints

  • 0 <= len(s) <= 200
  • s consists of English letters, digits, ' ', '+', '-', '.'

More from Meta DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.