# 8. String to Integer (atoi)

## 1.問題

## 2.想法

* 提問
  * 是不是只會輸出一個數字-> 不須轉換每個substring
  * 正負號
* function header, parameter
* test input
  * 空白 + 數字
  * integer overflow
* 說明想法
  * invalidate的情形:&#x20;
    * 字串 + 數字
    * 兩個正負號 + 數字
  * 忽略空白, 遇到正負號讀取後index + 1
  * 處理overflow
    * 加之前與加之後必須數值相同

```
backup = sum;
sum = sum * 10 + ans;
            
if (sum < 0 || backup != (sum - ans) / 10) {
   return sign > 0 ? INT_MAX : INT_MIN;
}
```

* 測試
* 計算複雜度: O(n)?

## 3.程式碼

```
class Solution {
public:
    int myAtoi(string str) {
        if (str.empty()) {
            return 0;
        }
        int size = str.length(), i = 0, sign = 1, sum = 0, backup = 0;
        
        //如果碰到空白就往後移
        while (i < size && str[i] == ' ') {
            i++;
        }
        
        //判斷符號
        if (str[i] == '+') {
            sign = 1;
            i++;
        } else if (str[i] == '-') {
            sign = -1;
            i++;
        }
        
        while (i < size && isdigit(str[i])) {
           
            int ans = int(str[i] - '0');
            backup = sum;
            sum = sum * 10 + ans;
            
            if (sum < 0 || backup != (sum - ans) / 10) {
                return sign > 0 ? INT_MAX : INT_MIN;
            }
            i++;
        }
        
        
        return sum * sign;
    }
};
```


---

# 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://jenhsuan.gitbook.io/algorithm/leetcode/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.
