DAY 3
0

# 7. Reverse Integer

## Question

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 `[-2^31, 2^31 - 1]`, then return `0`.

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

## Example

### Example1

``````Input: x = 123
Output: 321
``````

### Example2

``````Input: x = -123
Output: -321
``````

### Example3

``````Input: x = 120
Output: 21
``````

### Example4

``````Input: x = 0
Output: 0
``````

### Constraints

• `-2^31 <= x <= 2^31 - 1`

## 解題

### Think

• ver. 1
• rev存最後的結果，multiple是用來算目前10的次方是幾次。
• 在補上判斷是否超過範圍的if判斷式，就完工啦~
• 後來想想好像可以不用乘法的方式(ver. 2)。
• ver. 2
• rev也是存最後的結果，只是不用乘法，改用list的型態，將鏡像位址的元素交換，再轉回數字，中間有一行有一堆replace是為了把list轉str時，不需要的字串去掉。
• 但是結果發現好像沒有比較快XD。

### Code

#### Python

##### ver. 1
``````class Solution:
def reverse(self, x: int) -> int:
rev = 0
multiple = 0

if x < 0:
str_x = str(-x)
else:
str_x = str(x)

for index in range(len(str_x)):
rev += int(str_x[index])*(10**multiple)
multiple += 1

if x < 0:
rev = -rev

if (-2**31) > rev or rev > (2**31-1):
rev = 0

return rev
``````
##### ver. 2
``````class Solution:
def reverse(self, x: int) -> int:
rev = 0

if x < 0:
list_x = list(str(-x))
else:
list_x = list(str(x))
print(list_x)
for index in range(len(list_x)):
list_x[index], list_x[len(list_x)-index-1] = list_x[len(list_x)-index-1], list_x[index]

if (index-(len(list_x)-index-1)) == 0 or ((index+1) == (len(list_x)-index-1) and index == (len(list_x)-index-1)-1):
break

rev_str = str(list_x).replace(" ", "").replace(",", "").replace("[", "").replace("]", "").replace("'", "")

if x < 0:
rev = -int(rev_str)
else:
rev = int(rev_str)

if (-2**31) > rev or rev > (2**31-1):
rev = 0

``````

#### C

``````int reverse(int x){
long int rev = 0;

while(x != 0){
rev *= 10;
rev += (x%10);

x = x/10;
}

// INT_MIN: -2^31 = -2147483647-1
// INT_MAX: 2^31-1 = 2147483647
return (rev < INT_MIN || rev > INT_MAX)? 0 : rev;
}
``````

### Result

• Python

• ver. 1
• ver. 2
• C

30天 Leetcode解題之路30