5/02/2020

[LeetCode] 7. Reverse Integer

Problem : https://leetcode.com/problems/reverse-integer/

Since the valid signed integer number range is  -2 ** 31 to 2 ** 31 -1.
The code should not convert negative number to positive one.
And it should always check overflow before appending digits.

Time Complexity = O(log(x))
Space Complexity = O(1)
 
from math import fmod

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        result = 0

        max_int = 2 ** 31 - 1
        min_int = -2 ** 31

        while x != 0:
            remain = int(fmod(x, 10))
            
            if result > max_int // 10 or \
               (result == max_int // 10 and remain > max_int % 10):
                return 0

            if result < 0:
                min_remain = fmod(min_int, 10)
                if result < (min_int - min_remain) // 10 or \
                   (result == min_int and remain < min_remain):
                    return 0

            result = result * 10 + remain
            
            # Because python always does 'floor division'  
            # - 1 // 10 = -1 
            # Below formula convert it to (-1 - (-1)) // 10 = 0
            x = (x - remain) // 10

        return result

No comments:

Post a Comment