29. Divide Two Integers

public class Solution {
    public int divide(int dividend, int divisor) {
        boolean isNegtive=dividend<0&&divisor>0||dividend>0&&divisor<0;
        long ldividend=Math.abs((long)(dividend));
        long ldivisor=Math.abs((long)(divisor));
        long d=0, c=1, l=ldivisor;
        while((l<<1)<=ldividend)
        {
            l=l<<1;
            c=c<<1;
        }
        long ret=0;
        while(l>=ldivisor)
        {
            if(ldividend>=l)
            {
                ret+=c;
                ldividend-=l;
            }
            l=l>>1;
            c=c>>1;
        }
        ret=isNegtive?-ret:ret;
        if(ret>Integer.MAX_VALUE||ret<Integer.MIN_VALUE)
            return Integer.MAX_VALUE;
        return (int)ret;
    }
}

  

转载于:https://www.cnblogs.com/asuran/p/7580075.html

原文地址:https://www.cnblogs.com/twodog/p/12134781.html