LeetCode – Divide Two Integers (Java)

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


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


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;
        //calculate number of left shifts
        int numShift = 0;    
        //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;
        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:
String foo = "bar";
  • 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;



    return count;