> For the complete documentation index, see [llms.txt](https://imhuay.gitbook.io/studies/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://imhuay.gitbook.io/studies/algorithms/problems/2022/03/niu-ke-0057-jian-dan-fan-zhuan-shu-zi.md).

# 反转数字

![last modify](https://img.shields.io/static/v1?label=last%20modify\&message=2022-10-14%2014%3A59%3A33\&color=yellowgreen\&style=flat-square) [![](https://img.shields.io/static/v1?label=\&message=%E7%AE%80%E5%8D%95\&color=yellow\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/03/pages/R5NyOzkn3qAZy7wCx1pS#简单) [![](https://img.shields.io/static/v1?label=\&message=%E7%89%9B%E5%AE%A2\&color=green\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/03/pages/R5NyOzkn3qAZy7wCx1pS#牛客) [![](https://img.shields.io/static/v1?label=\&message=%E6%A8%A1%E6%8B%9F\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/03/pages/R5NyOzkn3qAZy7wCx1pS#模拟)

> [反转数字\_牛客题霸\_牛客网](https://www.nowcoder.com/practice/1a3de8b83d12437aa05694b90e02f47a)

**问题简述**

```
给定一个32位的有符号整数num，将num中的数字部分反转，最后返回反转的结果
1.只反转数字部分，符号位部分不反转
2.反转后整数num超过 32 位的有符号整数的范围 [−2^31,  2^31 − 1] ，返回 0
```

**思路**

* 要点：越界判断；
  * Python 中不会越界，直接跟边界比较即可；

<details>

<summary><strong>Python</strong></summary>

```python
class Solution:
    def reverse(self , x: int) -> int:
        sign = -1 if x < 0 else 1
        x = abs(x)
        
        ret = 0
        while x:
            c = x % 10
            ret = ret * 10 + c
            if ret > 2 ** 31 - 1:
                return 0
            x //= 10
        return ret * sign
```

</details>
