Leetcode 29. Divide Two Integers

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

If it is overflow, return MAX_INT.

 

思路,不用乘除和mod实现除法,比较容易的想到二分法。需要注意的是,sum+sum实现*2,当sum+sum> dividend时,用余数更新dividend (dividend = dividend - sum)。再就是注意Python的syntax: a if b else c。

 1 class Solution(object):
 2     def divide(self, dividend, divisor):
 3         """
 4         :type dividend: int
 5         :type divisor: int
 6         :rtype: int
 7         """
 8         if abs(dividend) < abs(divisor):
 9             return 0
10         sum = 0; count = 0; res = 0;
11         a = abs(dividend); b = abs(divisor)
12         while a>=b:
13             sum = b
14             count = 1
15             while sum+sum <= a:
16                 sum += sum
17                 count += count
18             a -= sum
19             res += count
20         if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0):
21             res = 0 - res
22         return 2147483647 if res > 2147483647 else res

 

posted @ 2017-02-27 02:13  lettuan  阅读(129)  评论(0编辑  收藏  举报