29. Divide Two Integers(medium)

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
Note:

Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 2^31 − 1 when the division result overflows.

分析:求两个数相除的商,题目要求不能使用乘法,除法和模运算。
容易想到此题可以用被除数不断去减除数,能够减多少次,商就为几。
但是这样的做法效率太低,可以不断的把除数扩大两倍然后相减,减少做减法的次数。使用移位扩大两倍效率更高。
设减的次数为p,如果被除数比除数的2倍还大的话,则把p左移一位,除数左移一位,不断把除数乘以2,直到不够减为止。这个循环减去了p次除数,商res += p,被除数要减掉t ,继续看被除数是否大于除数,如果大于,则还能继续减。

Java语言:

    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 divid = Math.abs((long) dividend), divis = Math.abs((long) divisor), res = 0;
        if (divis == 1) {
            return sign == 1 ? (int) divid : (int) -divid;
        }
        while (divid >= divis) {
            long t = divis, p = 1;
            while (divid >= (t << 1)) {
                t = t << 1;
                p = p << 1;
            }
            res += p;
            divid -= t;
        }
        return sign == 1 ? (int) res : (int) -res;
    }

你可能感兴趣的:(29. Divide Two Integers(medium))