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

  

posted @ 2017-09-23 06:22  Weiyu Wang  阅读(128)  评论(0编辑  收藏  举报