---
title: leetcode-string-to-integer-atoi
date: 2020-04-16 19:50:10
tags:
categories: leetcode
---

### 8. 字符串转换整数 (atoi)

[题目](https://leetcode-cn.com/problems/string-to-integer-atoi/)



<!--more-->



没什么好说的，注意各种情况，识别到数字之后就一直要是数字。



```python
class Solution:
  def myAtoi(self, str: str) -> int:
    p = ''
    str = str.lstrip()
    n = ''
    min_int = -2**31
    max_int = 2**31-1
    isnumeric = False
    for x in str:
      if not isnumeric and x == '-':
        p = '-'
        isnumeric = True
        continue
      if not isnumeric and x == '+':
        isnumeric = True
        continue
      if x.isnumeric():
        n += x
        isnumeric = True
      else:
        break
    if not n:
      return 0
    if int(n) > max_int:
      if p:
        return min_int
      else:
        return max_int
    p += n
    return int(p)
# 32 ms	13.6 MB
```

