LeetCode - flip integer

Given a 32-bit signed integer, invert the numbers in the integer.

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        flag = 1
        if x < 0 :
            flag = -1
            x = abs(x)
        x = str(x)
        list1 = list(x)
        list1.reverse()
        string = "".join(list1)
        x = int(string)
        if x in range(-2**31, 2**31):
            return x*flag
        else:
            return 0

First judge the positive and negative, if the negative number is assigned flag=-1, take the absolute value, flip it,
convert the absolute value to a string and then convert it to a list, reverse the order,
convert it back to a string,
convert it to an integer
, multiply the flag, and get back the positive and negative attributes
Judging whether it is out of bounds, the out-of-bounds return 0

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325568733&siteId=291194637