Divide Two Integers

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


The idea is to use bit operations.  The key point is carefully handling corner cases.


public int divide(int dividend, int divisor) {
    if(dividend == 0){
        return 0;
    }
      
    long div = dividend;
    div = dividend>0?div:-div;
    long vis = divisor;
    vis = divisor>0?vis:-vis;
      
    int result = 0;
    while(div>=vis){
        long r = 1;
        long v = vis;
        while(div>=v){
            v<<=1;
            r<<=1;
        }
        v>>>=1;
        r>>>=1;
        div -= v;
        result+=r;
    }
    return (dividend>0&&divisor>0) || (dividend<0&&divisor<0) ? result:-result;
}


你可能感兴趣的:(LeetCode)