29. Divide Two Integers/两数相除

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: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231− 1 when the division result overflows.

AC代码

class Solution {
public:
    int divide(int dividend, int divisor) {
 //     if (dividend == 0) return 0;  //加了这行运行时间 0ms
        bool minus = false;
        if (dividend > 0 && divisor < 0 || dividend < 0 && divisor > 0)
            minus = true;
        long long a = labs((long)dividend);
        long long b = labs((long)divisor);
        long long ans = 0;
        while (a >= b) {
            long long nb = b, q = 1;
            while (a > (nb << 1)) {
                nb <<= 1;
                q <<= 1;
            }
            a -= nb;
            ans += q;
        }
        if (minus) ans = 0 - ans;
        if (ans > INT_MAX || ans < INT_MIN) ans = INT_MAX;
        return ans;
    }
};

总结

你可能感兴趣的:(29. Divide Two Integers/两数相除)