转载:https://blog.csdn.net/Lynn_Baby/article/details/80624180 

 

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3
Example 2:

Input: dividend = 7, divisor = -3
Output: -2

 

乘除取模都不让用。。那只有加减

 

思路解析:

判空,返回0
使用long类型的变量存储division和divisor的绝对值
如果除数小于被除数,返回0
使用加法完成除法,注意保存加了多少倍,使用嵌套循环,外层控制division大于divisor,里层控制倍数增加一倍是否比division要小
最后返回值的时候不要忘记注意正负号

public int divide(int dividend, int divisor) {
        if (dividend == 0 || divisor == 0)
            return 0;
        boolean flag = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0);
        long a = Math.abs((long) dividend);// 注意要转换成long型,防止溢出
        long b = Math.abs((long) divisor);
        if (a < b)
            return 0;
        int result = 0;
        while (a >= b) {
            long tempSum = b;
            long divSum = 1;
            while (tempSum + tempSum <= a) {
                tempSum += tempSum;
                divSum += divSum;
            }
            a -= tempSum;
            result += divSum;
        }
        return flag == true ? -result : result;
    }

 

posted on 2019-01-22 11:37  反光的小鱼儿  阅读(251)  评论(0编辑  收藏  举报