---
# System prepended metadata

title: Leetcode --- Reverse Integer(Easy)
tags: [Leetcode, Easy]

---

Leetcode --- Reverse Integer(Easy)
===

## Description

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).**

### Examples:

Ex1:
**Input:** x = 123
**Output:** 321

Ex2:
**Input:** x = -123
**Output:** -321

Ex3:
**Input:** x = 2147483647
**Output:** 0
**Explanation:** Overflow

### Constrains:

* -2^31^ <= x <= 2^31^ - 1

## Solutions

### Method 1: 轉成字串處理
```java=
class Solution {
    public int reverse(int x) {
        String ans = x>= 0 ? new StringBuilder(Integer.toString(x)).reverse().toString() : new StringBuilder(Integer.toString(Math.abs(x))).append("-").reverse().toString();
    
        try
        {
            return Integer.parseInt(ans);
        }
        catch(Exception e)
        {
            return 0;
        }
    }
}
```

line 3: 等同於
```java
if(x >=0)
{
    String s = Integer.toString(x);
    StringBuilder sb = new StringBuilder(s);
    sb.reverse(); // StringBuilder's method
    String ans = sb.toString();
}
else
{
    String s = Integer.toString(-x);  //去負號
    StringBuilder sb = new StringBuilder(s);
    sb.append("-"); //append:再字尾加字
    sb.reverse(); // StringBuilder's method
    String ans = sb.toString();
}
```

### *Note: ==Integer.toString()== 與 ==String.vauleOf()== 基本上無差異*

### Complexity Analysis

Depend on **.toString()** or **.reverse()**

### Submissions on Leetcode
Runtime: **2 ms**, faster than **27.39%** of Java online submissions for Reverse Integer.
Memory Usage: **35.9 MB**, less than **69.89%** of Java online submissions for Reverse Integer.

## Method 2: POP,PUSH digits

直接對數字做分析,一整串數字拆成一個一個digits做翻轉,甚至可以不用用到*Stack*或*Array*完成POP,PUSH的操作,像這樣
```java
//POP
x %=10;
x /=10;
//PUSH
ans = ans *10 + x;
```
而Overflow的處理,將ans存成long型態再比較是否超出int的範圍.

```java=
class Solution {
    public int reverse(int x) {
         long res = 0;
        while (x != 0) 
		{
            res = res * 10 + x % 10;
            System.out.println(res);
            x = x / 10;
        }
        
        if (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) {
            return 0;
        } else {
            return (int)res;
        }
    }
}
```

### Complexity Analysis
每次除10 
=> **O(log~10~n)**

### Submissions on Leetcode
Runtime: **1 ms**, faster than **100.00%** of Java online submissions for Reverse Integer.
Memory Usage: **36.1MB**, less than **42.60%** of Java online submissions for Reverse Integer.

###### tags: `Leetcode` `Easy`