How to reverse integer output in python

步履不停
Release: 2019-07-03 13:42:18
Original
16817 people have browsed it

How to reverse integer output in python

Given a 32-bit signed integer, return its inverted integer

Example 1:
 
Input: 123
Output: 321
Copy after login
Example 2:
 
Input: -123
Output: -321
Copy after login
Example 3:
 
Input: 120
Output: 21
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!