---
# System prepended metadata

title: 8. String to Integer (atoi)
tags: ['8', leetcode, medium]

---

# 8. String to Integer (atoi)

###### tags: `leetcode` `8` `medium` 

## :memo:  Question
題目很多字自己去看。

## :memo: leetcode solution
* :medal: **思考一**: 題目我覺得就是單純的邏輯判斷，要看仔細題目給你的邏輯，考細心程度，我也是 submit 兩次才成功。

```python=
class Solution:
    def myAtoi(self, s: str) -> int:
        if not s or (s[0] != '+' and s[0] != '-' and s[0] != ' ' and not s[0].isdigit()):
            return 0
        
        stack = []
        
        for i in s:
            if i == ' ' and not stack:
                continue
            elif i == '+' and not stack:
                stack.append(i)
            elif i == '-' and not stack:
                stack.append(i)
            elif i.isdigit():
                stack.append(i)
            else:
                break
                
        if not stack or (len(stack) == 1 and not stack[0].isdigit()):
            return 0
        
        if -(2**31) < int("".join(stack)) < 2**31-1:
            return int("".join(stack))
        elif int("".join(stack)) <= -(2**31):
            return -(2**31)
        else:
            return 2**31-1
```

## :memo: bigO
* 時間複雜度: 最差就是 O(s)
* 空間複雜度: 最差就是 O(s)