Skip to content

Latest commit

 

History

History
73 lines (53 loc) · 2.75 KB

7.Reverse_Integer(Medium).md

File metadata and controls

73 lines (53 loc) · 2.75 KB

7. Reverse Integer (Medium)

Date and Time: Sep 3, 2024, 22:21 (EST)

Link: https://leetcode.com/problems/reverse-integer/


Question:

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:

  • -2^31 <= x <= 2^31 - 1

Walk-through:

  1. We use is_negative to know if x < 0 or not. res to store the reversed x.

  2. We know % can get x's last digit, and each time we can res * 10 and add the last digit of x to update res, and update x //= 10, so we can shorten x to get the next digit.

  3. Lastly, we check if the reversed x res is in the range [-2^31, 2^31-1], if not, we return 0. (Only check the reversed x)

  4. Then, we return res and negate it depends on is_negative.


Python Solution:

class Solution:
    def reverse(self, x: int) -> int:
        res = 0
        is_negative = False
        # Check if x is negative number
        if x < 0:
            x = -x
            is_negative = True
        # Reversing
        while x > 0:
            res = res * 10 + (x % 10)
            x //= 10
        # Check if the reversed x is within the range
        if (is_negative and -res < -2**31) or (not is_negative and res > 2**31-1):
            return 0
        
        return -res if is_negative else res

Time Complexity: $O(n)$, n is the length of x.
Space Complexity: $O(n)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms