Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-144

String to Integer (atoi)

Problem

Implement atoi: skip leading spaces, read an optional plus or minus sign, then read digits until a non-digit appears, and return the parsed integer clamped to the signed 32-bit range.

If no digits are read the result is 0; values beyond the range saturate at the boundary. Ignore any trailing characters.

Hint

The sign is only consumed if it immediately follows the leading whitespace.

Test cases

case 1
in: ["42"]
expected: 42
case 2
in: [" -42"]
expected: -42
case 3
in: ["4193 with words"]
expected: 4193
case 4
in: ["words and 987"]
expected: 0
case 5
in: ["-91283472332"]
expected: -2147483648
case 6
in: ["+1"]
expected: 1
Starter codePython
def my_atoi(s):
    # Your code here
    pass

6 test cases · run your code against them in the editor