Home > Article > Backend Development > How to reverse integer output in python
Given a 32-bit signed integer, return its inverted integer
Example 1: Input: 123 Output: 321
Example 2: Input: -123 Output: -321
Example 3: Input: 120 Output: 21
Assume that the size range of the integer is:, if the inverted integer overflows, then Return 0.
1: The normal integer method is implemented by using the remainder*10 accumulation method. It should be noted that Python uses a "round down" mechanism for integer division, so positive numbers and negative numbers must be operated differently.
def reverse(self, x): """ :type x: int :rtype: int """ num = 0 if x == 0: return 0 if x < 0: x = -x while x != 0: num = num*10 + x%10 x = x/10 num = -num else: while x != 0: num = num*10 + x%10 x = x/10 if num>pow(2,31)-1 or num < pow(-2,31): return 0 return num
2: Convert an integer to a string, reverse the string, and then convert it to an integer again
def reverse(self, x): """ :type x: int :rtype: int """ plus_minus = "" reverse_x = "" if x<0: plus_minus = "-" x = -x for i in str(x): reverse_x = i + reverse_x reverse_x = plus_minus +reverse_x if int(reverse_x)>pow(2,31)-1 or int(reverse_x)<pow(-2,31): return 0
Recommended related tutorials: Python video tutorial
The above is the detailed content of How to reverse integer output in python. For more information, please follow other related articles on the PHP Chinese website!