Lin Ma
Lin Ma

Reputation: 10139

overflow handle in Python

Working on below algorithm puzzle and it requires to handle situation of overflow. I am confused by this line, min(max(-2147483648, res), 2147483647), if anyone could comment how it handles overflow, it will be great. :)

BTW, I am still confused why there will be overflow in Python when we are doing two integer divide calculation?

Post detailed problem statement and solutions,

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

class Solution:
# @return an integer
def divide(self, dividend, divisor):
    positive = (dividend < 0) is (divisor < 0)
    dividend, divisor = abs(dividend), abs(divisor)
    res = 0
    while dividend >= divisor:
        temp, i = divisor, 1
        while dividend >= temp:
            dividend -= temp
            res += i
            i <<= 1
            temp <<= 1
    if not positive:
        res = -res
    return min(max(-2147483648, res), 2147483647)

Upvotes: 0

Views: 2178

Answers (1)

poke
poke

Reputation: 387677

min(max(-2147483648, res), 2147483647)

This is a combination of these two things:

result = max(-2147483648, res)
min(result, 2147483647)

The functions max and min return the maximum and minimum number respectively of those that are passed to them.

In the case of the max() call, if res is above -2147483648, then the value of res is returned. Otherwise, if the number is lower, then that big negative number is returned. This ensures that the lowest number that is returned from the max() call is -2147483648. If res is larger, fine, otherwise it will take that number as the lowest boundary.

The min() call does exactly the opposite. It establishes a maximum boundary of 2147483647 by returning that number if res is larger than it.

Combined, those function calls make sure that -2147483648 <= res <= 2147483647.

Finally note, that in Python, integers are not really limited in size. So those boundaries are just enforced without actually being needed (at least for Python), so if this is required for the puzzle solution, it’s probably a requirement by the puzzle.

Upvotes: 2

Related Questions