Trans int to str to solve the Problem (Python)


  • 0
    T

    Str is much easier to handle than signed int.

    class Solution(object):
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            if x >= 0:
                str_x = str(x)
                str_x_invert = str_x[::-1]
                x_invert = int(str_x_invert)
                if x_invert > 2**31 - 1:
                    return 0
                else:
                    return x_invert
            else:
                x = -x
                str_x = str(x)
                str_x_invert = str_x[::-1]
                x_invert = -int(str_x_invert)
                if x_invert < -2**31:
                    return 0
                else:
                    return x_invert
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.