29. Divide Two Integers
problem description
Input: dividend = 10, divisor = 3
Output: 3Input: dividend = 7, divisor = -3
Output: -2algorithm thought
code
class Solution {
public:
int divide(int dividend, int divisor) {
if(dividend==INT_MIN&&divisor==-1)
return INT_MAX;
long dd=labs(dividend);
long di=labs(divisor);
long res=0;
while(dd>=di){
long tmp=di, m=1;
while(tmp<<1<=dd){
tmp=tmp<<1;
m=m<<1;
}
dd-=tmp;
res+=m;
}
return dividend>0^divisor>0?-res:res;
}
};algorithm analysis
Last updated