> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# String to Integer (atoi) Python Solution

> Tested Python solution for LeetCode 8 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 8, Medium. Topics: String. [View on LeetCode](https://leetcode.com/problems/string-to-integer-atoi/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 8   # by problem number
lcpy gen -s string_to_integer_atoi   # by problem name
```

## Problem

Implement the `my_atoi(string s)` function, which converts a string to a 32-bit signed integer.

The algorithm for `my_atoi(string s)` is as follows:

1. **Whitespace**: Ignore any leading whitespace (` `).
2. **Signedness**: Determine the sign by checking if the next character is `-` or `+`, assuming positivity if neither present.
3. **Conversion**: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
4. **Rounding**: If the integer is out of the 32-bit signed integer range `[-2^31, 2^31 - 1]`, then round the integer to remain in the range. Specifically, integers less than `-2^31` should be rounded to `-2^31`, and integers greater than `2^31 - 1` should be rounded to `2^31 - 1`.

Return the integer as the final result.

### Examples

```
Input: s = "42"
Output: 42
```

**Explanation:**

```
The underlined characters are what is read in and the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
         ^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "42" ("42" is read in)
           ^
```

```
Input: s = "   -042"
Output: -42
```

**Explanation:**

```
Step 1: "   -042" (leading whitespace is read and ignored)
            ^
Step 2: "   -042" ('-' is read, so the result should be negative)
             ^
Step 3: "   -042" ("042" is read in, leading zeros ignored in the result)
               ^
```

```
Input: s = "1337c0d3"
Output: 1337
```

**Explanation:**

```
Step 1: "1337c0d3" (no characters read because there is no leading whitespace)
         ^
Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit)
             ^
```

```
Input: s = "0-1"
Output: 0
```

**Explanation:**

```
Step 1: "0-1" (no characters read because there is no leading whitespace)
         ^
Step 2: "0-1" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "0-1" ("0" is read in; reading stops because the next character is a non-digit)
          ^
```

```
Input: s = "words and 987"
Output: 0
```

**Explanation:** Reading stops at the first non-digit character 'w'.

### Constraints

* `0 <= s.length <= 200`
* `s` consists of English letters (lower-case and upper-case), digits (0-9), ` `, `+`, `-`, and `.`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/string_to_integer_atoi/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/string_to_integer_atoi/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def my_atoi(self, s: str) -> int:
        i = 0
        n = len(s)

        # Skip whitespace
        while i < n and s[i] == " ":
            i += 1

        if i == n:
            return 0

        # Check sign
        sign = 1
        if s[i] in {"+", "-"}:
            sign = -1 if s[i] == "-" else 1
            i += 1

        # Convert digits
        result = 0
        while i < n and s[i].isdigit():
            result = result * 10 + int(s[i])
            i += 1

        result *= sign

        # Clamp to 32-bit range
        return max(-(2**31), min(2**31 - 1, result))
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(n) | O(1)  |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind).
