Divide Two Integers

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

If it is overflow, return MAX_INT.

    public int divide(int dividend, int divisor) {
        //边界
        if (divisor==0||(dividend==Integer.MIN_VALUE&&divisor==-1)) return Integer.MAX_VALUE;
        //符号
        int sign = (dividend<0)^(divisor<0)?-1:1;
        long m = Math.abs((long)dividend);
        long n = Math.abs((long)divisor);
        int res = 0;
        while (m>=n){
            int shift = 0;

            while (m>=(n<<shift)){
                shift++;
            }

            res += 1<<(shift-1);
            m -= n<<(shift-1);
        }

        return res=sign==1?res:-res;
    }
原文地址:https://www.cnblogs.com/bingo2-here/p/7878922.html