Reverse Integer

Question

Reverse digits of an integer.

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

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

Tags

  • Mathematics
  • String

Thought

Two approaches:

  1. Use maths
  2. Use string

The implementations for these two approaches are below.

Code

Use maths

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0:
            return 0
        queue = []
        absX = abs(x)
        while absX:
            queue.append(absX % 10)
            absX /= 10
        ans = 0
        while queue:
            ans = ans * 10 + queue.pop(0)
        if ans >= 2**31:
            return 0
        return (x / abs(x)) * ans

Use string

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0:
            return 0
        neg = x / abs(x)
        strX = list(str(abs(x)))
        result = int(''.join(reversed(strX)))
        if result >= 2**31:
            return 0
        return neg * result

results matching ""

    No results matching ""