LeetCode has a Medium coding Problem in Its’ Algorithm Section in Python “Reverse Integer”. Today We are going to solve this problem. LeetCode Link of the Problem is HERE

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 [-231, 231 - 1]
, then return 0
.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Examples
Input: x = 123 Output: 321
Input: x = -123 Output: -321
Input: x = 120 Output: 21
Constraints:
-231 <= x <= 231 - 1
Solution to Python Reverse Integer
The Skeleton Code given in LeetCode is
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
Firstly, Check for the number either given input is -ve or +ve
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
neg= False
if( x < 0):
neg = True
x = -x
Secondly, Declare one more variable reversed_number. Reversed Number storing the Previous Numbers + current Digit. It is the variable which we will return at the end of the program. Start a loop and run it until the given input reaches zero.
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
neg= False
if( x < 0):
neg = True
x = -x
Reversed_Number = 0
while( x != 0):
digit = x % 10
Reversed_Number = (Reversed_Number * 10) + digit
Thirdly, Check for the Reverse if it overflows. Remember that Our question condition is that our reverse should also be a 32-bit integer. If the reverse is not a 32-bit integer we should return 0.
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
neg= False
if( x < 0):
neg = True
x = -x
Reversed_Number = 0
while( x != 0):
digit = x % 10
Reversed_Number = (Reversed_Number * 10) + digit
if(Reversed_Number >= 2147483647 or Reversed_Number <= -2147483647):
return 0
Finally, Divide x again until it reaches 0 when x == 0 the Loop will break and we have to return the reversed Number. Check for the Negative flag too, if Negative flag is True return Negative of Number else return Positive.
Complete Solution:
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
neg= False
if( x < 0):
neg = True
x = -x
Reversed_Number = 0
while( x != 0):
digit = x % 10
Reversed_Number = (Reversed_Number * 10) + digit
if(Reversed_Number >= 2147483647 or Reversed_Number <= -2147483647):
return 0
x = x // 10
if neg:
return -Reversed_Number
return Reversed_Number
READ MORE
Python-related posts Visit HERE
C++ related posts Visit HERE
Databases related posts Visit HERE
Data Structures related posts visit HERE
Algorithms related posts visit HERE
Data Science related posts visit HERE