Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Difficulty: Medium
public class Solution {
public long helper(long dividend, long divisor){
if(dividend < divisor) return 0;
long ans = 0;
long curr = divisor, count = 1;
while(dividend >= divisor){
curr = divisor; count = 1;
while(dividend >= curr){
dividend = (dividend - curr);
ans = (ans + count);
curr = curr * 2;
count = count * 2;
}
}
return ans;
}
public int divide(int dividend, int divisor) {
if(divisor == 0) return Integer.MAX_VALUE;
if(dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
if(dividend == 0) return 0;
if(divisor == Integer.MIN_VALUE) return dividend == Integer.MIN_VALUE ? 1 : 0;
int flag = 0;
if((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)){
flag = 1;
}
else{
flag = -1;
}
if(dividend == Integer.MIN_VALUE){
long ans = (helper((long)(Math.abs(dividend + 1)) + 1, (long)(Math.abs(divisor))));
if(ans == (long)(Integer.MAX_VALUE) + 1){
return Integer.MIN_VALUE;
}
return (int)(ans) * flag;
}
return (int)(helper((long)(Math.abs(dividend)), (long)(Math.abs(divisor)))) * flag;
}
}