leetcode

Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

The idea is dividend = divisor*2(i0) + divisor*2(i1) + divisor*2(i2) ...

so we need to find result = 2(i0) + 2(i1) + 2(i2) + .. using bit operation and multiple them.

public int divide(int dividend, int divisor) {
        if(divisor==0) {
            return 0;
        }        
        if(divisor==1) {
            return dividend;
        }        
        if (dividend==divisor) {
            return 1;
        }
        if (divisor==2) {
            return dividend>>1;
        }

        int result = 0;  
        if(dividend==Integer.MIN_VALUE) {  
            result = 1;  
            dividend += Math.abs(divisor);  
        }  

        if(divisor==Integer.MIN_VALUE) {
            return result;  
        }

        boolean isNegative = false;
        if (dividend>0&&divisor<0 || dividend<0&&divisor>0) {
            isNegative = true;
        }

        //if dividend==MIN_VALUE, abs will still show negative
        long a=Math.abs((long)dividend);
        long b=Math.abs((long)divisor);

        while (a>=b) {
            long temp = b;            
            for (int i=1; a>=temp; i<<=1, temp<<=1) {
                a-=temp;
                result+=i;
            }            
        }

        return (isNegative?-result:result);
    }