> For the complete documentation index, see [llms.txt](https://mm.ricky.moe/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mm.ricky.moe/algorithm/algorithm-and-data-structure/leetcode/7.-zheng-shu-fan-zhuan.md).

# 7. 整数反转

## 题目

给出一个 32 位的有符号整数，你需要将这个整数中每位上的数字进行反转。

**示例 1:**

```
输入: 123
输出: 321
```

&#x20;**示例 2:**

```
输入: -123
输出: -321
```

**示例 3:**

```
输入: 120
输出: 21
```

**注意:**

假设我们的环境只能存储得下 32 位的有符号整数，则其数值范围为 \[−231,  231 − 1]。请根据这个假设，如果反转后整数溢出那么就返回 0。

## JavaScript实现

1. 转换为string后逆序转换
2. 对于-号进行预处理
3. 对于溢出的数字return前处理

```javascript
/*
 * @lc app=leetcode.cn id=7 lang=javascript
 *
 * [7] 整数反转
 */
/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    const s = x.toString()
    let reverseS = ''
    s[0] === '-' ? reverseS+='-': null
    for (let i = s.length-1; i >=0; i--) {
      if(s[i] === '-') continue
      reverseS += s[i]
    }

    const reverseInt = parseInt(reverseS)
    if(reverseInt<-Math.pow(2,31) || reverseInt>Math.pow(2,31)-1){
      return 0
    }else{
      return reverseInt
    }
};


```


---

# 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, and the optional `goal` query parameter:

```
GET https://mm.ricky.moe/algorithm/algorithm-and-data-structure/leetcode/7.-zheng-shu-fan-zhuan.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
