1 """ 2 Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. 3 Return the quotient after dividing dividend by divisor. 4 The integer division should truncate toward zero. 5 Example 1: 6 Input: dividend = 10, divisor = 3 7 Output: 3 8 Example 2: 9 Input: dividend = 7, divisor = -3 10 Output: -2 11 """ 12 """ 13 正确答案,先减第一个,再减double 14 """ 15 class Solution: 16 def divide(self, dividend: int, divisor: int) -> int: 17 res = 0 18 positive = (dividend < 0) is (divisor < 0) 19 dividend = abs(dividend) 20 divisor = abs(divisor) 21 while dividend >= divisor: 22 temp, i = divisor, 1 23 while dividend >= temp: #多加了一层循环,是为了避免超时 24 res += i 25 dividend -= temp 26 i = 2*i 27 temp = 2*temp 28 if not positive: 29 res = - res 30 return min(max(-2147483648, res), 2147483647) #!!!这个范围限制很巧妙 31 32 """ 33 我的答案,一个一个减会超时 34 """ 35 class Solution: 36 def divide(self, dividend, divisor): 37 neg = 0 38 res = 0 39 if dividend > 0 and divisor < 0 or divisor > 0 and dividend < 0: 40 neg = 1 41 dividend = abs(dividend) 42 divisor = abs(divisor) 43 while dividend >= divisor: 44 dividend = dividend - divisor 45 res += 1 46 if neg: 47 res = - res 48 return min(max(-2147483648, res), 2147483647)