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

# 7. Reverse Integer

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MeO3Gk76l2r6k4FZ_7N%2F-MeOWoBl0lhrYv1dAqze%2Fimage.png?alt=media\&token=87c7e6c1-661c-48ae-bdeb-3df14bb114c8)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MeO3Gk76l2r6k4FZ_7N%2F-MeOWyAN5ubdL1nzKf9f%2Fimage.png?alt=media\&token=ebbfea75-2a5f-471d-bb57-2d1cd437e4e3)

Remembering the formula:

```
res = res*10 + x%10 (remainder)
x /=10
```

notice the boundary

time: O(n)

space: O(1)

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