# 整数反转 - Reverse Integer

## 007. 整数反转 - Reverse Integer

【栈】 【纯数学】

``````给出一个 32 位的有符号整数，你需要将这个整数中每位上的数字进行反转。
``````

### Example:

``````输入: 123

``````

``````输入: -123

``````

``````输入: 120

``````

## Solution

### Solution 【栈】【转字符串操作】 ( 33ms)

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 `````` ``````class Solution { public int reverse(int x) { long result = 0; String str = String.valueOf(x); Stack stack = new Stack<>(); for (int i = 0; i < str.length(); i++) stack.push(str.charAt(i)); str = ""; while (stack.size() > 1) str += stack.pop(); if (stack.peek() != '-') { str += stack.pop(); result = Long.parseLong(str); } else result = -Long.parseLong(str); return x; } } ``````

### Solution 【纯数学】 ( 15ms)

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 `````` ``````class Solution { public int reverse(int x) { int result = 0; while(x != 0){ if(result > Integer.MAX_VALUE / 10 || result < Integer.MIN_VALUE / 10) return 0; result = result * 10 + x % 10; x /= 10; } return result; } } ``````

### Solution 【纯数学】 ( 12ms)

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 `````` ``````int reverse(int x) { if (x == 0) return 0; int abs = x > 0 ? x : -x; // 取绝对值 int digit; long ans = 0; int max = 0X7FFFFFFF, min = 0X80000000; // 补码 (2^31-1=2147483647,-2^31=-2147483648) while (abs > 0) { // 反转 digit = abs % 10; // 取个位 ans = ans * 10 + digit; abs /= 10; } if (x < 0) ans = -ans; // 原值为负 if (x > 0) { // 溢出判断 if (ans > max) return 0; } else { if (ans < min) return 0; } return ans; // 返回值从long转为int } ``````