---
# System prepended metadata

title: 0008. String to Integer (atoi)
tags: [Leetcode, FaceBook, Medium]

---

# 0008. String to Integer (atoi)
###### tags: `Leetcode` `Medium` `FaceBook`
Link: https://leetcode.com/problems/string-to-integer-atoi/

## 思路
按照题目要求做就好了 没什么技巧
注意一些edge case integer超范围怎么办~

## Code
```java=
class Solution {
    public int myAtoi(String s) {
        s = s.trim();
        int res = 0;
        if(s.length()==0) return res;
        int len = 0;
        int idx = 0;
        boolean negative = false;
        if(s.charAt(idx)=='-'){
            negative = true;
            idx++;
        }
        else if(s.charAt(idx)=='+'){
            idx++;
        }
        for(int i = idx;i < s.length();i++){
            if(!Character.isDigit(s.charAt(i))){
                break;
            }
            int num = s.charAt(i)-'0';
            
            if(len>=9){
                if(res>Integer.MAX_VALUE/10 ||(res==Integer.MAX_VALUE/10&&((negative&&num>=8)||(!negative&&num>=7)))){
                    return negative?Integer.MIN_VALUE:Integer.MAX_VALUE;
                }
            }
            
            res = res*10+num;
            len++;
        }
        res = negative?-res:res;
        return res;
    }
}
```