# 7. Reverse Integer

## 1.問題

![](/files/-LLKRYeN3l40kuslTmRS)

## 2.想法

* 提問
* function header, parameter
* test input: integer overflow
* 說明想法
  * 直覺想法: 將每個位數放進vector後, 再加回答案
  * 改進做法: 每次疊代就將原還得值處以10, 但要記得處理overflow
* 測試
* 計算複雜度: O(n)?

## 3.程式碼

* 直覺想法

```
class Solution {
public:
    int reverse(int x) {
        int index = 1, sum = 0;
        vector<int> res;
        while (int(abs(x) / pow(10, index - 1)) > 0) {
            res.push_back(int(abs(x) % int(pow(10, index)) / pow(10, index - 1)));
            index++;
        }
        for (int i = 0; i < res.size(); i++) {
            sum += res[i] * pow(10, index - 2);
            index--;
        }
        if (0 > sum) {
                return 0;
            }
        return x < 0 ? -sum : sum;
    }
};
```

* 改進做法

```
class Solution {
public:
    int reverse(int x) {
        int index = 1, sum = 0;
        int t = abs(x);
        while (t > 0) {
            if(sum > INT_MAX/10 || sum<INT_MIN/10){
                return 0;
            }
            int res = t % 10;
            sum = sum * 10 + res;
            t = t /10;
        }
        
        return x < 0 ? -sum : sum;
    }
};
```

## 4.Performance


---

# 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/7.-reverse-integer.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.
