Concise Python code

  • 0
    class Solution:
        # @return an integer
        def reverse(self, x):
            s = str(x)
            s = s[::-1]
            if s[len(s)-1] == '-':
                if -int(s[:len(s)-1]) < -math.pow(2,31):
                    return 0
                return -int(s[:len(s)-1])
            if int(s) >= math.pow(2,31):
                return 0
            return int(s)

  • 5

    here is much more concise solution. if overflow return 0, If not add the sign of the original number and return the reversed absolute value

    def reverse(self, x):
      revx = int(str(abs(x))[::-1]) #reverse the abs(x) and convert to int
      return 0 if revx>math.pow(2,31) else revx * cmp(x,0)

  • 0

    Ever shorter, working in Python 3 too.

    def reverse(self, x):
         r = int(str(abs(x))[::-1])
         return (2*(x>0)-1)*(r<2**31)*r

Log in to reply

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