:orphan: Reverse Integer =============== .. highlight:: none Problem ------- https://leetcode.com/problems/reverse-integer/ 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``\ :sup:```31```\ ``, 2``\ :sup:```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:** - ``-2``\ :sup:```31```\ ``<= x <= 2``\ :sup:```31```\ ``- 1`` .. highlight:: python Pattern ------- Math Solution -------- Extract the sign of ``x``. We can use modulus and division to get the digits of ``x``. Reverse the list of digits. Then check that the digits are in the range :math:`[2^{31} - 1, -2^{31}]`. If so, calculate the reversed integer using the expansion .. math:: r = \\sum_{i=0}^{n-1} 10^i d_i. Code ---- .. literalinclude:: ../problems/medium/reverse-integer/reverse_integer__approach_1.py :language: python :lines: 12- Test ---- >>> from reverse_integer__approach_1 import reverse >>> reverse(123) 321 >>> reverse(-123) -321 >>> reverse(120) 21 Complexity ---------- | Time: :math:`O(\log_{10} x)` — extract each digit, reverse list of digits, and calculate reversed integer | Auxiliary Space: :math:`O(\log_{10} x)` — digits list .. autofunction:: reverse_integer__approach_1.reverse .. autofunction:: reverse_integer__approach_1.too_large