# 7.Reverse Integer <span class='tag' data-diff="easy"></span>
{%hackmd RN5D4nggQRO8wzNqxuvlNw %}
## 題目
Given a 32-bit signed integer, reverse digits of an integer.
**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: $[−2^{31}, 2^{31} − 1]$. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
## 思路
```javascript
var reverse = function(x) {
let sign = x < 0 ? -1 : 1;
let value = sign * Number(Math.abs(x).toString().split("").reverse().join(""));
if(value > 2**31 - 1 || value < -1 * 2**31 ) value = 0;
return value ;
};
```
這一題真的很簡單,只要轉成字串、反轉再轉回Int即可,但要注意題目中有特別針對overflow的情況要求回傳值,由於javascript中Number物件是以IEEE 754中規範的64bit雙精度浮點數來儲存的,範圍可以到 $[-(2^{53}-1), (2^{53}-1)]$ ,所以需要主動判斷是否有溢位。