> For the complete documentation index, see [llms.txt](https://docs-57.gitbook.io/data-structure-and-algorithms/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs-57.gitbook.io/data-structure-and-algorithms/problems/bit-manipulation/reverse-number.md).

# Reverse Number

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

```

#### Constraints:

`-231 <= x <= 231 - 1`

### Solution

```csharp
public int Reverse(int x) {
    long result = 0;
    while (x != 0) {
        result = result * 10 + x % 10;
        x /= 10;
        if (result > Int32.MaxValue || result < Int32.MinValue) {
            return 0;
        }
    }
    return (int)result;
}

```

The time complexity of the algorithm is **O(log(x))**, where x is the input to the function. This is because in each iteration of the while loop, we’re dividing `x` by `10`, effectively reducing the problem size by a factor of `10`. Hence, the number of iterations is proportional to the number of digits in x, which is log(x) in base 10.

The space complexity of the algorithm is **O(1)**, which means it uses a constant amount of space. This is because we’re only using a fixed number of variables and not any data structures that grow with the size of the input. The integer result and the input x are the only variables being used, and their size does not change with different inputs.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs-57.gitbook.io/data-structure-and-algorithms/problems/bit-manipulation/reverse-number.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
