---
description: 再一次練習數字切割，而不是轉字串又轉陣列後運算
---

# # 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;

};
```
