Reverse digits of an integer.

Example1: x = 123, return 321 Example2: x = -123, return -321

click to show spoilers.

Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.


In [5]:
class Solution(object):
    def reverse(self, t):
        """
        :type x: int
        :rtype: int
        """
        ret = ""
        is_neg = False
        
        if (-t) > 0:
            is_neg = True
            t = -t

        # 2. Extract each trailing digit and remove it
        while t > 1:        
            r = (t % 10)                 
            t = t  / 10
            
            if ret == 0:
                continue 
            ret = ret + chr(48+int(r))

        if int(ret) > 2**31:
            return 0

        # 3. If needed, add the negative sign
        if is_neg:
            ret = chr(45) + ret

        return int(ret)
        
print (Solution().reverse(-1003))


-3001

In [ ]: