Python solution without converting int to string with overflow checks


  • 0

    This solution uses simple math.

    class Solution(object):
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            if x > 2**31 or x < -2**31:
                return 0
            reverse = 0
            neg = 1 if x > 0 else -1
            loop = x*neg
            
            while loop > 0:
                reverse = reverse*10 + loop%10
                loop /= 10
            if reverse > 2**31 or reverse < -2**31:
                return 0
            return neg*reverse
    

Log in to reply
 

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