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)