Question: http://oj.leetcode.com/problems/divide-two-integers/

Question Name: Divide Two Integers

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | class Solution: # @return an integer def divide(self, dividend, divisor): # Handle the special case that, dividend is zero if dividend == 0: return 0 # Handle the special case that, divisor is zero if divisor == 0: raise ZeroDivisionError() result = 0 # Final result # Determine the sign of final result, and convert # dividend or/and divisor into positive integer. positive = True if dividend < 0: dividend = -dividend positive = (not positive) if divisor < 0: divisor = -divisor positive = (not positive) # Enlarge the divisor as long as it is <= dividend step = divisor stepRes = 1 while (step << 1) <= dividend: step = step << 1 stepRes = stepRes << 1 while step >= divisor: while dividend >= step: dividend -= step result += stepRes # If current step is too large, try a smaller # step (divisor). step = step >> 1 stepRes = stepRes >> 1 if positive: return result else: return -result |