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;
    }
}

10 thoughts on “LeetCode – Divide Two Integers (Java)”

  1. 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.

  2. 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;
    }

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

  4. 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;

    }

Leave a Comment