Home>Article>Backend Development> How to reverse integer output in python

How to reverse integer output in python

步履不停
步履不停 Original
2019-07-03 13:42:18 16803browse

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)
      

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn