---
# System prepended metadata

title: '[7. Reverse Integer](https://leetcode.com/problems/reverse-integer/)'
tags: [medium, leetcode, Math]

---

###### tags: `leetcode` `medium` `Math`
# [7. Reverse Integer](https://leetcode.com/problems/reverse-integer/)

## 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
### Example 1:

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

### Example 2:

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

### Example 3:

**Input**: x = 120  
**Output**: 21  

## Constraints:

- $-2^{31} \leq x \leq 2^{31} - 1$

## Code

```c=
#include <limits.h>

int reverse(int x) {
    int* check = malloc(sizeof(int));
    int negative = (x < 0), first = x % 10, remain = x / 10, res = 0;
    while (remain != 0) {
        // By negative number or not checking whether it will get overflow after times 10
        if (negative ? (INT_MIN / 10 <= res) : (INT_MAX / 10 >= res)) {
            res *= 10;
            // By negative number or not checking whether it will get overflow after plus first
            if (negative ? (INT_MIN - first <= res) : (INT_MAX - first >= res))
                res += first;
            else
                return 0;
        }

        else
            return 0;
        // Re-update first and remain
        first = remain % 10;
        remain = remain / 10;
    }

    // If there still has any un-operating number in first
    if (first != 0) {
        if (negative ? (INT_MIN / 10 <= res) : (INT_MAX / 10 >= res)) {
            res *= 10;
            if (negative ? (INT_MIN - first <= res) : (INT_MAX - first >= res))
                return res += first;
        }

        else
            return 0;
    }

    return res;
}
```


## Complexity

|Space |Time  |
|-     |-     |
|$O(1)$|$O(N)$|

## Result

- Runtime : 0ms, 100%  
- Memory usage : 5.7mb, 36.75%