LeetCode – Divide Two Integers (Java)

Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT.

Analysis

This problem can be solved based on the fact that any number can be converted to the format of the following:

```num=a_0*2^0+a_1*2^1+a_2*2^2+...+a_n*2^n
```

The time complexity is O(logn).

Java Solution

```public int divide(int dividend, int divisor) { //handle special cases if(divisor==0) return Integer.MAX_VALUE; if(divisor==-1 && dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE;   //get positive values long pDividend = Math.abs((long)dividend); long pDivisor = Math.abs((long)divisor);   int result = 0; while(pDividend>=pDivisor){ //calculate number of left shifts int numShift = 0; while(pDividend>=(pDivisor<<numShift)){ numShift++; }   //dividend minus the largest shifted divisor result += 1<<(numShift-1); pDividend -= (pDivisor<<(numShift-1)); }   if((dividend>0 && divisor>0) || (dividend<0 && divisor<0)){ return result; }else{ return -result; } }```
Category >> Algorithms >> Interview
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• Sai Nikhil

I think he meant TLE (Time Limit Exceeded)

• Tanmay Misra

You are using multiplication in the solution.

• Ray

Why the complexity would be O(logn), can you explain more about it? Thank you.

• mdlamar

Only problem with this approach is when you get something like 100000000/1 it is really slow cause it has to loop that many times.

• This code takes care of everything-

public static int divide(int dividend, int divisor) {
if(divisor == 0) {
return Integer.MAX_VALUE;
} else if(dividend == 0) {
return 0;
}
int sign = 1;
if(divisor < 0) {
sign *= -1;
divisor *= -1;
}
if(divisor == 1) {
return sign*dividend;
}
if(dividend < 0) {
sign *= -1;
dividend *= -1;
}

int sum = 0, count = -1;
while(sum <= dividend) {
sum += divisor;
count++;
}
return count*sign;
}

• dev

if dividend is 0 then ? i think a cross check on dividend will be better

• Juan Carlos Alvarez

What is LTE?. I like Saurabh solution better, it’s more elegant.

• Candis

I tried the same code using ‘int’ for absolue values of dividend and divisor. How come that is giving me ‘Timeout; error??

• nelson

The solution would lead to LTE; nevertheless, the code is really concise

• Thank you for this code, but I think this can be solved using sum as follows –

public int divide(int dividend, int divisor) {

int sum = 0, count = -1;

while(sum <= dividend) {

sum += divisor;

count++;

}

return count;

}