# 7. 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 `[-2**31, 2**31 - 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
``````

Example 4:

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

Constraints:

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

## 解法解析

1. 將數值轉換成字串後做反轉，然後再轉回數值。有些程式語言有預設的函數或語法糖可以讓這件事變得很方便，像 JavaScript、Python、Swift
2. 第二種方式可以減少空間複雜度，因為只需要儲存單一變數。直接做遍歷，每次除 10 取商數當作下一個遍歷的變數，把餘數作為新的位數來用。其中比較要注意的是在每一次的遍歷中要去判斷是否超過了答案限定的範圍。

### 解法範例

#### Go

``````import "math"

func reverse(x int) int {
var rev int = 0
for x != 0 {
pop := x % 10
x /= 10
if rev > math.MaxInt32/10 || (rev == math.MaxInt32/10 && pop > 7) {
return 0
}
if rev < math.MinInt32/10 || (rev == math.MinInt32/10 && pop < -8) {
return 0
}
rev = rev*10 + pop
}
return rev
}
``````

#### JavaScript

``````/**
* @param {number} x
* @return {number}
*/
var reverse = function (x) {
const isNeg = 0 > x ? -1 : 1;
let rev = 0;
let absx = Math.abs(x);
while (absx > 0) {
rev = rev * 10 + (absx % 10);
absx = Math.floor(absx / 10);
if (rev > Math.pow(2, 31) - 1) return 0;
}
return rev * isNeg;
};
``````
``````var reverse = function (x) {
const isNegative = x < 0 ? -1 : 1;
const reverseN = Number(
Math.abs(x).toString().split('').reverse().join('')
);
if (reverseN > 0x7fffffff) return 0;
return reverseN * isNegative || 0;
};
``````

#### Kotlin

``````class Solution {
fun reverse(x: Int): Int {
var result = 0L
var tmp = x
while (tmp != 0) {
result = result * 10 + tmp % 10
tmp /= 10
}
return if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) 0 else result.toInt()
}
}
``````

#### PHP

``````class Solution
{

/**
* @param Integer \$x
* @return Integer
*/
function reverse(\$x)
{
\$rev = 0;
while (\$x != 0) {
\$pop = \$x % 10;
\$x = (int) (\$x / 10);
if (\$rev > 214748364 || (\$rev == 214748364 && \$pop > 7)) {
return 0;
}
if (\$rev < -214748364 || (\$rev == -214748364 && \$pop < -8)) {
return 0;
}
\$rev = \$rev * 10 + \$pop;
}
return \$rev;
}
}
``````

#### Python

``````class Solution:
def reverse(self, x: int) -> int:
"""
:type x: int
:rtype: int
"""
if x > 0:
result = int(str(x)[::-1])
else:
result = -1 * int(str(-x)[::-1])

if result > (2**31 - 1) or result < -(2**31):
result = 0
return result
``````

#### Rust

``````impl Solution {
pub fn reverse(x: i32) -> i32 {
let negative = x < 0;

let mut rev = 0i32;
let mut x = x.abs();

while x > 0 {
let pop = x % 10;
let next_scale = rev.checked_mul(10);
if next_scale.is_none() {
return 0;
}
rev = next_scale.unwrap() + pop;
x /= 10;
}

if negative { -rev } else { rev }
}
}
``````

#### Swift

``````class Solution {
func reverse(_ x: Int) -> Int {
var rev = 0
var x = x

while x != 0 {
rev = rev * 10 + x % 10
x = x / 10
guard rev >= Int32.min && rev <= Int32.max else {
return 0
}
}
return rev
}
}
``````
``````class Solution {
func reverse(_ x: Int) -> Int {
let negative = x < 0 ? -1 : 1
let result = Int(String(String(abs(x)).reversed())) ?? 0
if result > Int(pow(2.0, 31)) {
return 0
}
return result * negative
}
}
``````