# 8. String to Integer (atoi)

```java
class Solution {
    public int myAtoi(String s) {
        int sign =1;
        int index=0;
        
        //ignore lead whitesapce
        while(index<s.length() && s.charAt(index)==' '){
            index++;
        }
        
        // check sign
        if(index<s.length() && s.charAt(index)=='+'){
            index++;
        }else if (index<s.length() && s.charAt(index) == '-'){
            index++;
            sign = -1;
        }
        
        int result = 0;
        // move pointer until it reaches the firt non-digit char
        while(index<s.length() && s.charAt(index)>='0' && s.charAt(index)<='9'){
            int digit = s.charAt(index)-'0';
            
            // Key: if reuslt is just equal to MIN_VALUE will be return from here, 
            // if result is just equal to MAX_VALUE, will be return outside the while loop
            if (Integer.MAX_VALUE/10<result || 
                (Integer.MAX_VALUE/10==result && Integer.MAX_VALUE%10<digit)){
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }

            result=result*10+digit;
            index++;
        }
        
        return sign*result;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ucan.gitbook.io/notes/8.-string-to-integer-atoi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
