---
# System prepended metadata

title: 7-Reverse integer
tags: [Medium]

---

# 7-Reverse integer
###### tags: `Medium`
## Question
![](https://i.imgur.com/v1hEm7f.png)
https://leetcode.com/problems/reverse-integer/

## Solution
### Sol. 1
- 想法:字串直接反轉，再補正負號
```python=
def reversDigits(num):
    sign = 1
    if num < 0:
        sign = -1
    # converting number to string
    string = str(abs(num))
 
    # reversing the string
    string = list(string)
    string.reverse()
    string = ''.join(string)
 
    # converting string to integer
    num = int(string)*sign
 
    # returning integer
    return num

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        x_rev = reversDigits(x)
        if x_rev > 2**31-1 or x_rev < -2**31:
            return 0
        else:
            return x_rev 
        
``` 
### Sol. 1
- 用餘數找出每個位數，再乘10倍加回去
```python=
    def reverse(self, x):
        num=0
        num_dis=abs(x)
        while(num_dis):
            temp=num_dis%10
            num_dis=(num_dis-temp)//10
            if num==0:
                num=temp
            else:
                num=(num*10)+temp
        if x<0:
            num=num*(-1)
        return num if num > -2**31 and num < 2**31-1 else 0
```
### C++ Sol.
```cpp=
class Solution {
public:
    int reverse(int x) {
        long num = 0;
        int y = abs(x);
        while(y != 0)
        {
            int r = y%10;
            y = (y-r)/10;
            num = r + num*10;
        }
        if(x < 0)
        {
            num = (-1)*num;
        }
        if( -1*pow(2,31) <= num && num <= pow(2,31)-1)
        {
            return num;
        }
        else
        {
            return 0;
        }
        
    }
};
```