Reverse Integer

Problem Id: 7 Difficulty: Easy Tag: Math


Intuition

Simply use % operater to revert the integer.

Pay attention to negtative integer.

Solution


class Solution:
    def reverse(self, origin: int) -> int:
        neg = origin < 0
        origin = abs(origin)
        target = 0
        while origin:
            target = target * 10 + origin % 10
            origin = origin // 10

        if neg:
            target = - target
        if not -(2 ** 31) <= target <= (2 ** 31 - 1):
            return 0
        return target