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;
    }
};

总结

无

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容