# 把字符串转换成整数(atoi)

![last modify](https://img.shields.io/static/v1?label=last%20modify\&message=2022-10-14%2014%3A59%3A33\&color=yellowgreen\&style=flat-square) [![](https://img.shields.io/static/v1?label=\&message=%E4%B8%AD%E7%AD%89\&color=yellow\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/..#中等) [![](https://img.shields.io/static/v1?label=\&message=%E7%89%9B%E5%AE%A2\&color=green\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/..#牛客) [![](https://img.shields.io/static/v1?label=\&message=%E5%AD%97%E7%AC%A6%E4%B8%B2\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/..#字符串) [![](https://img.shields.io/static/v1?label=\&message=%E7%BB%8F%E5%85%B8\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/..#经典)

> [把字符串转换成整数(atoi)\_牛客题霸\_牛客网](https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f)

**问题简述**

```
写一个函数 StrToInt，实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。传入的字符串可能有以下部分组成:
1.若干空格
2.（可选）一个符号字符（'+' 或 '-'）
3. 数字，字母，符号，空格组成的字符串表达式
4. 若干空格
```

**思路**

* 设定一个指针逐字符处理；

<details>

<summary><strong>Python</strong></summary>

```python
class Solution:
    def StrToInt(self , s: str) -> int:
        
        N = len(s)
        if N <= 0: return 0

        p = 0
        sign = 1
        
        # 注意越界判断
        # 跳过空格
        while p < N and s[p] == ' ': p += 1
        if p < N and s[p] == '-': sign = -1
        if p < N and s[p] in ('-', '+'): p += 1
        
        flag = False
        ret = 0
        while p < N and '0' <= s[p] <= '9':
            ret = ret * 10 + int(s[p])
            if ret >= 2 ** 31:  # python 没有越界，人工判断
                flag = True
                break
            p += 1
        
        if flag:
            return 2 ** 31 - 1 if sign == 1 else -2 ** 31

        return ret * sign
```

</details>

<details>

<summary><strong>C++</strong></summary>

```cpp
class Solution {
public:
    int StrToInt(string str) {
        // write code here
        int n = str.length();
        if (n < 1) return 0;
        
        int p = 0;      // 模拟指针
        int sign = 1;   // 正负
        
        // C++ 字符串不需要越界判断
        while (isspace(str[p]))  p++;  // 跳过前置空格
        if (str[p] == '-') sign = -1;
        if (str[p] == '-' || str[p] == '+') p++;
        
        int ret = 0;
        while (str[p] >= '0' && str[p] <= '9') {
            int new_ret = ret * 10 + str[p] - '0';
            if (new_ret / 10 != ret) {  // 越界判断
                return sign > 0? INT_MAX : INT_MIN;
            }
            ret = new_ret;
            p++;
        }
        
        return sign * ret;
    }
};
```

</details>
