【LeetCode with Python】 Divide Two Integers

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/divide-two-integers/
题目类型:
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/39453293

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):
        
        if 0 == divisor or 0 == dividend:
            return 0
        elif 1 == divisor or -1 == divisor:
            return dividend * divisor
            return -dividend

        positive = 1
        if (dividend >0 and divisor < 0) or (dividend < 0 and divisor > 0):
            positive = -1
        dividend = dividend if dividend > 0 else -dividend
        divisor = divisor if divisor > 0 else -divisor

        result = 0
        dividend_now = dividend
        while dividend_now >= divisor:
            total = divisor
            sub_result = 1
            while True:
                total = total << 1
                sub_result = sub_result << 1   ## not += 2
                if total > dividend_now:
                    total = total >> 1
                    sub_result = sub_result >> 1
                    break
                elif total == dividend_now:
                    break
            result += sub_result
            dividend_now -= total
        return result * positive

你可能感兴趣的:(LeetCode,LeetCode,python,python,with)