Instagram
youtube
Facebook
Twitter

Reverse Integer Leetcode Solution

In this tutorial, we are going to solve reverse integer problems from leetcode in python.

Task:

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 [-231, 231 - 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:

class Solution:
    def reverse(self, x: int) -> int:
        s = str(x)
        if s[0] == '-':
            m = -1
            s = s[1:]
        else:
            m=1 
        a = m*(int(s[::-1]))
        if a in range(-2**31, 2**31):
            return a
        else:
            return 0

Steps:

step1: first we change the type of our integer to string.

step2: Then, we check if the integer is negative or positive then assign the variable m and s accordingly.

step3: Now, reverse the integer with the help of its string type and assign it to as int type multiplied by variable m.

step4: Then, we check the range of the new reversed integer and return it accordingly.