[Leetcode]Divide Two Integers

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

If it is overflow, return MAX_INT.

class Solution {
public:
/*algorithm binary search
*/
int bSearch(long d1,long d2){
long l = 1,h = d1;
while(l <= h){
long m = (l+h)>>1;
long d = d1 - m*d2;
if(0 <= d && d < d2){
return m;
}else if(d >= d2){
l = m+1;
}else{
h = m-1;
}
}
}
int divide(int dividend, int divisor) {
long d1 = labs(dividend),d2 = labs(divisor);//use labs,instead of abs,or -
bool neg = (dividend^divisor)>>sizeof(int)*8-1;//d1<0&&d2 >0 || d1>0||d2<0
if(d1 == 0 || d1 < d2)return 0;
if(d2 == 1 && d1 > INT_MAX)return neg?-d1:INT_MAX;
long count=bSearch(d1,d2);
return neg?-count:count;
}
};

LeetCode --- 29. Divide Two Integers

2015-02-02 21:58:27

Divide Two Integers -- LeetCode

2014-02-27 05:41:54

(LeetCode) Divide Two Integers (Java)思路讲解及实现

2015-09-30 15:52:53

[Leetcode]29. Divide Two Integers @python

2016-01-16 16:48:08

LeetCode 29 Divide Two Integers (C,C++,Java,Python)

2015-05-13 09:27:20

LeetCode29DivideTwoIntegers--In Java

2016-02-22 20:24:54

leetcode 29 -- Divide Two Integers

2015-06-12 17:23:05

LeetCode(29)Divide Two Integers

2014-01-03 07:24:18

leetcode——Divide Two Integers 不用乘除取余操作求除法（AC）

2014-06-09 20:19:43

[LeetCode]29.Divide Two Integers

2015-01-25 10:41:25