If it is overflow, return MAX_INT.
Idea: The basic idea is to double the divisor when using dividend to minus the divisor. There are a lot of details to be taken care in this problem.
Special Case 1: The divisor may be 0.
Special Case 2: When the dividend==Integer.MIN_VALUE, the divisor==-1, the quotient will also overflow.
I first remove the Special Case 1. Then judge the result will be whether positive or negative. Then transfer the absolute value of the dividend and the divisor to long integer type. Keep subtracting the divisor from the dividend and double the divisor for next subtraction. When the dividend becomes less than the original divisor (before any double), the loop is stopped and the Special Case 2 is handled.
It will also be OK to handle the Special Case 2 at the beginning of the program.
Time: O(lgn) Space: O(1)
Code:
public class Solution {
public int divide(int dividend, int divisor) {
if(divisor==0)
return Integer.MAX_VALUE;
boolean negative=false;
if((dividend<0&&divisor>0)||(dividend>0&&divisor<0))
negative=true;
long dend=Math.abs((long)dividend);
long sor=Math.abs((long)divisor);
long qua=0;
while(dend>=sor)
{
long start=sor;
long mul=1;
while(dend>=start)
{
dend=dend-start;
qua=qua+mul;
start=start+start;
mul=mul+mul;
}
}
if(negative)
return -(int)qua;
else
{
if(qua>Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else
return (int)qua;
}
}
}
No comments:
Post a Comment