Divide two integers without using multiplication, division and mod operator.
public int divide(int dividend, int divisor) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(divisor == 0 || dividend == 0){
return 0;
}
boolean negative = (dividend<0) ^ (divisor<0);
long a = abs(dividend);
long b = abs(divisor);
int finalCount = 0;
int count = 0;
while(a>=b){
count = 1;
b = abs(divisor);
long sum = b;
while(sum+sum <= a){
sum += sum;
count += count;
}
a -= sum;
finalCount += count;
};
if(negative){
return 0 - finalCount;
}else{
return finalCount;
}
}
private long abs(int num){
if(num < 0){
return -(long)num;
}
return (long)num;
}