不用乘除和mod,算两个整数相除

//  5.2
//  Divide Two Integers
//  Divide two integers without using multiplication, division and mod operator.
//  If it is overflow, return MAX_INT.
    public static int divide(int dividend, int divisor) {
        int tempDividend = Math.abs(dividend);
        int tempDivisor = Math.abs(divisor);
        if (tempDividend == Integer.MIN_VALUE) {
            tempDividend = Integer.MAX_VALUE;
        }
        if (tempDivisor == Integer.MIN_VALUE) {
            tempDivisor = Integer.MAX_VALUE;
        }
        if (divisor == 0) {
            return Integer.MAX_VALUE;
        } else if (tempDividend < tempDivisor || tempDivisor == 0) {
            return 0;
        }
        int flag = dividend > 0 && divisor < 0 || dividend < 0 && divisor > 0 ? -1 : 1;
        if (flag == 1) {
            return divideRes(tempDividend, tempDivisor);
        } else {
            return -divideRes(tempDividend, tempDivisor);
        }
    }
    static public int divideRes(int dividend, int divisor) {
        if (dividend < divisor) {
            return 0;
        }
        int sum = divisor;
        int mul = 1;
        while ((sum + sum) < dividend) {
            sum += sum;
            mul += mul;
        }
        return mul + divideRes(dividend - sum, divisor);
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容