← All coding problems
String to Integer (atoi)
mediumStrings+20 XPTime limit 2s
Convert a string to a 32-bit signed integer, the way C's atoi does:
- Skip leading spaces.
- Read an optional
+or-sign (at most one). - Read digits until the first non-digit character or the end of the string. Everything after that is ignored. If no digits were read, the result is
0. - Apply the sign. If the number is outside the 32-bit range
[−2³¹, 2³¹ − 1], clamp it: below the range →−2147483648, above →2147483647.
Input: one line s (letters, digits, spaces, +, - and .; it contains at least one non-space character).
Output: the resulting integer.
Constraints: 1 ≤ length of s ≤ 200.
Examples: 42 → 42; -042 → -42; 1337c0d3 → 1337; 0-1 → 0; words 987 → 0; -91283472332 → -2147483648.
Sample input 1
42
Sample output 1
42
Sample input 2
-042
Sample output 2
-42
Sample input 3
1337c0d3
Sample output 3
1337
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).