Reverse Integer in Python

PythonServer Side ProgrammingProgramming

Suppose we have one 32-bit signed integer number. We have to take the number and reverse the digits. So if the number is like 425, then the output will be 524. Another thing we have to keep in mind that the number is signed, so there may be some negative numbers. So if the number is –425, then it will be –524.

Here we have some assumptions. We have assumed that we are using in the domain of 32-bit signed integer. So the range will be [-232 to 232 – 1]. So if the number is not in range, then the function will return 0.

To solve this, we will use the Python Code. At first we will convert the given integer into string. So if the first character in the string is ‘-’, then the number is negative number, so reverse from index 1 to index length – 1. And finally convert them to integer before returning it, for positive number, simply reverse the string and make it integer before returning. In each case we will check whether the number is in range of 32-bit integers. If it exceeds the range, then simply return 0.

Let us see the implementation to get better understanding

Example

 Live Demo

class Solution(object):
   def reverse(self, x):
      """
      :type x: int
      :rtype: int
      """
      x = str(x)
      if x[0] == '-':
         a = int('-' + x[-1:0:-1])
         if a >= -2147483648 and a<= 2147483647:
            return a
         else:
            return 0
         else:
            a = int(x[::-1])
            if a >= -2147483648 and a<= 2147483647:
               return a
            else:
               return 0
ob1 = Solution()
print(ob1.reverse(-425))

Input

print(ob1.reverse(-425))

Output

-524
raja
Published on 08-Jan-2020 15:01:50
Advertisements