Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
求两数相除,不能用乘法,除法和取余操作。
解法:位操作Bit Operation, Time: O(logn)
num=a_0*2^0+a_1*2^1+a_2*2^2+...+a_n*2^n
Java:
public int divide(int dividend, int divisor) { //handle special cases if(divisor==0) return Integer.MAX_VALUE; if(divisor==-1 && dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE; //get positive values long pDividend = Math.abs((long)dividend); long pDivisor = Math.abs((long)divisor); int result = 0; while(pDividend>=pDivisor){ //calculate number of left shifts int numShift = 0; while(pDividend>=(pDivisor<<numShift)){ numShift++; } //dividend minus the largest shifted divisor result += 1<<(numShift-1); pDividend -= (pDivisor<<(numShift-1)); } if((dividend>0 && divisor>0) || (dividend<0 && divisor<0)){ return result; }else{ return -result; } }
Python:
class Solution: def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ result, dvd, dvs = 0, abs(dividend), abs(divisor) while dvd >= dvs: inc = dvs i = 0 while dvd >= inc: dvd -= inc result += 1 << i inc <<= 1 i += 1 if dividend > 0 and divisor < 0 or dividend < 0 and divisor > 0: return -result else: return result if __name__ == "__main__": print(Solution().divide(123, 12)) print(Solution().divide(123, -12)) print(Solution().divide(-123, 12)) print(Solution().divide(-123, -12))
Python:
class Solution: def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ 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)
C++:
class Solution { public: int divide(int dividend, int divisor) { long long m = abs((long long)dividend), n = abs((long long)divisor), res = 0; if (m < n) return 0; while (m >= n) { long long t = n, p = 1; while (m > (t << 1)) { t <<= 1; p <<= 1; } res += p; m -= t; } if ((dividend < 0) ^ (divisor < 0)) res = -res; return res > INT_MAX ? INT_MAX : res; } };
C++:
class Solution { public: int divide(int dividend, int divisor) { long long res = 0; long long m = abs((long long)dividend), n = abs((long long)divisor); if (m < n) return 0; long long t = n, p = 1; while (m > (t << 1)) { t <<= 1; p <<= 1; } res += p + divide(m - t, n); if ((dividend < 0) ^ (divisor < 0)) res = -res; return res > INT_MAX ? INT_MAX : res; } };