29. 两数相除

2020-06-24  本文已影响0人  justonemoretry

自己解法

自己的解法,想着是不能乘除和mod的话,就只有用加减运算了,于是写了个循环减除法的解法,这个解法显然没通过,因为如果是除以1的话,基本要循环千万级别次。参考题解中,其实思路还是用减法去算,只是引入了位运算,每次都减去除数 乘以 2的n次方,等于是用移位变向地实现了乘法运算,下面上解法。

class Solution {

    public int divide(int dividend, int divisor) {

        boolean sign = (dividend > 0) ^ (divisor > 0);

        // 统一转成负数处理,负数最小值是2的整数次方

        if (dividend > 0) {

            dividend = -dividend;

        }

        if (divisor > 0) {

            divisor = -divisor;

        }

        int result = 0;

        while (dividend <= divisor) {

            int tempResult = -1;

            int tempDivisor = divisor;

            while (dividend <= tempDivisor << 1) {

                if (tempDivisor <= Integer.MIN_VALUE >> 1) {

                    break;

                }

                tempResult = tempResult << 1;

                tempDivisor = tempDivisor << 1;

            }

            dividend -= tempDivisor;

            result += tempResult;        

        }

        if (!sign) {

            if (result <= Integer.MIN_VALUE) {

                return Integer.MAX_VALUE;

            }

            result = -result;

        }

        return result;

    }

}

上一篇 下一篇

猜你喜欢

热点阅读