
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Reverse Integer in Python
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
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
- Related Articles
- Reverse an Integer in Java
- Python program to reverse bits of a positive integer number?
- How to reverse of integer array in android listview?
- Reverse String in Python
- JavaScript Reverse the order of the bits in a given integer
- Reverse Linked List in Python
- Reverse Only Letters in Python
- Reverse String II in Python
- Java program to reverse bits of a positive integer number
- Reverse digits of an integer in JavaScript without using array or string methods
- How to use Array Reverse Sort Functions for Integer and Strings in Golang?
- Roman to Integer in Python
- Reverse Vowels of a String in Python
- How to reverse a number in Python?
- How to reverse a string in Python?
