> For the complete documentation index, see [llms.txt](https://txfs19260817.gitbook.io/leetcode-go-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://txfs19260817.gitbook.io/leetcode-go-notes/solutions/7.-reverse-integer.md).

# 7. Reverse Integer

## LeetCode [7. Reverse Integer](https://github.com/txfs19260817/LeetCode-Go/blob/master/solutions/title/README.md)

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

**Example 1:**

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

**Constraints:**

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

### Tags

Math

### Solution

Our goal is to move units digit of `x` to the end of `ans`. We can achieve this by performing `ans = ans*10 + x%10; x /= 10` until `x == 0`. After this loop, we need to check if the result is out of the signed 32-bit integer range. If it does go outside of the range, we return 0 rather than `ans`.

### Complexity

* Time complexity: $$O(n)$$
* Space complexity: $$O(1)$$

### Code

```go
func reverse(x int) int {
	var ans int
	for ; x != 0; x /= 10 {
		ans = ans*10 + x%10
	}
	if ans > 1<<31-1 || ans < -(1<<31) {
		return 0
	}
	return ans
}
```
