String to Integer (atoi)

Implement myAtoi(s), which converts a string to a 32-bit signed integer: skip leading spaces, read an optional + or - sign, then read digits until a non-digit or the end of the string (no digits means 0). Clamp the value to the range [-2^31, 2^31 - 1] and return it.

30:00

String to Integer (atoi)
medium
Free written solution
Topics
Companies

Implement myAtoi(s), which converts a string to a 32-bit signed integer: skip leading spaces, read an optional + or - sign, then read digits until a non-digit or the end of the string (no digits means 0). Clamp the value to the range [-2^31, 2^31 - 1] and return it.

Example 1:
Input: {"s":"42"}
Output: 42
Constraints:
  • 0≤s.length≤2000 \leq s.\text{length} \leq 200

  • s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"42"}

Put the cursor i at index 0 of a 2-character string. The parse runs in stages: spaces, sign, digits.

1. skip spaces

→

2. sign

→

3. digits

→

4. clamp / return

s, read left to right by cursor i

4

0

2

1

end

· = space (skipped)

■ sign

■ digits used

■ stop

result vs the 32-bit limit

INT_MAX

2

1

4

7

4

8

3

6

4

7

result

0

sign +1

digit -

(INT_MAX - digit) // 10 -

Variables
VariableValue
i0
n2
DepthFunction Call
Stack empty
0/9