> For the complete documentation index, see [llms.txt](https://hannahpun.gitbook.io/leetcode-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hannahpun.gitbook.io/leetcode-note/math/7-reverse-integer.md).

# # 7 Reverse Integer

[LeetCode](https://leetcode.com/problems/reverse-integer/)

```
Given a 32-bit signed integer, reverse digits of an integer.
// 32-bite 
// Math.pow(2, 31);
```

```
Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit 
signed integer range: [−231,  231 − 1]. 
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
*/

/** 
* 一個一個拉出來換
* 321 for example
* get 1 result = 1
* get 2 result = 1*10 + 2
* get 3 result = 12+10 + 3
// 完全不同方向思考
*/

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {}
```

### 怎麼解

數字一個一個拉出來換，從後面開始(個位數)．例如 321

* get 1 result = 321%10 = 1
* *get 2 result = Math.floor(* 321/10) % 10
* get 3 result  = *Math.floor(321/ 100) % 10*

```
var reverse = function(x) {
    let INT_MAX = Math.pow(2, 31);
    let reverse = 0;
    // save negative or not 
    let flag = x > 0 ? 1 : -1;//
    x = Math.abs(x);
    while(x != 0) {
        reverse = reverse*10 + x%10;
        x = Math.floor(x/10);
    }
    if(reverse > INT_MAX || reverse < INT_MAX*-1){
        return 0;
    }
    return reverse*flag;

};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://hannahpun.gitbook.io/leetcode-note/math/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.
