LeetCode 7: Reverse Integer

link

Like in atoi, we detect if there will be an overflow or an underflow before including the next digit.

Time: \mathcal{O}(1), space: \mathcal{O}(1).

class Solution:
    def reverse(self, x: int) -> int:
        def digits(x):
            while x != 0:
                digit = x % 10
                yield digit

                x //= 10

        max_pos = 2_147_483_647
        min_neg = -2_147_483_648
        max_mag_tenth = 2_147_483_64

        if x == min_neg:
            return 0
            
        sign = -1 if x < 0 else 1
        x = abs(x)
        num = 0
        for d in digits(x):
            if num > max_mag_tenth:
                return 0
            if num == max_mag_tenth:
                if sign == 1:
                    if d == 7:
                        return max_pos
                    if d > 7:
                        return 0    
                if sign == -1:
                    if d == 8:
                        return min_neg
                    if d > 8:
                        return 0
                
            num = 10*num + d
                

        return sign * num

Leave a comment