123-7. 整数反转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。(照旧前三个我写的,后面我抄的.看人家前几名写的代码就是一种享受啊)

示例 1:

class Solution(object):
    def reverse1(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0 or x == -0:
            return 0

        num_str = str(x)
        min_sign = ""
        if num_str.startswith("-"):
            min_sign = "-"
            num_str = num_str.replace("-", "")
        num_str = num_str[::-1]

        while num_str.startswith("0"):
            num_str = num_str.replace("0", "", 1)

        if min_sign:
            num_str = min_sign + num_str

        num = int(num_str)
        if (2**31 - 1) > num > -2 ** 31:
            return num
        return -1

    def reverse2(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0 or x == -0:
            return 0

        num_str = str(x)
        min_sign = ""
        if num_str.startswith("-"):
            min_sign = "-"
            num_str = num_str.replace("-", "")

        num_list = [item for item in num_str]
        i = 0
        j = len(num_str)-1
        while i <= j:
            temp = ord(num_list[j]) + ord(num_list[i])
            num_list[i] = chr(temp - ord(num_list[i]))
            num_list[j] = chr(temp - ord(num_list[i]))
            i += 1
            j -= 1

        num_str = "".join(num_list)
        if min_sign:
            num_str = min_sign + num_str

        num = int(num_str)
        if (2**31 - 1) > num > -2 ** 31:
            return num
        return num if (2**31 - 1) > num > -2 ** 31 else 0

    def reverse0(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0:
            return 0

        str_x = str(abs(x))[::-1]
        ret_num = int(str_x)

        if x < 0:
            ret_num = -ret_num

        return ret_num if (2**31 - 1) > ret_num > -2 ** 31 else 0

    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        flag = False
        if x < 0:
            x = abs(x)
            flag = True
        ret = 0
        while x:
            val = x % 10
            x = x // 10
            ret = 10 * ret + val
        if flag == True:
            ret = -ret
        return ret if ret >= -2**31 and ret <= 2**31 -1  else 0


if __name__ == '__main__':
    s = Solution()
    nums1 = 1230
    print(s.reverse(nums1))
posted @ 2020-12-31 11:05  楠海  阅读(146)  评论(0)    收藏  举报