---
# System prepended metadata

title: 7. Reverse Integer
tags: [math, Leetcode, medium, python]

---

###### tags: `Leetcode` `medium` `math` `python`

# 7. Reverse Integer

## [題目連結:] https://leetcode.com/problems/reverse-integer/

## 題目:
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**


**Example 1:**
```
Input: x = 123
Output: 321
```
**Example 2:**
```
Input: x = -123
Output: -321
```
**Example 3:**
```
Input: x = 120
Output: 21
```

## 解題想法:
* 轉成string在reverse,再轉回int
* 注意正負與益位

## python:
``` python=
#outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        #先判斷正負:
        if x<0:
            #reversed
            ans = -1*int(str(-x)[::-1])
            #判斷是否溢位
            return 0 if ans<(-2**31) else ans
        else:
            ans = int(str(x)[::-1])
            return 0 if ans>(2**31) else ans

if __name__ == '__main__':
    result = Solution()
    x = 120
    ans = result.reverse(x)
    print(ans)
```