29. Divide Two Integers

Posted 暗影侠客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了29. Divide Two Integers相关的知识,希望对你有一定的参考价值。

29. Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

 

这题真的无能为力,js写法一直超时,思路很简单,都是位运算。下面给个别人c++过的代码

class Solution {
public:
    int divide(int dividend, int divisor) {

       //注意这里的long long ,因为整数最小值 取负会溢出
        long long m = abs((long long)dividend), n = abs((long long)divisor), res = 0;
        if (m < n) return 0;    
        while (m >= n) {
            long long t = n, p = 1;
            while (m > (t << 1)) {
                t <<= 1;
                p <<= 1;
            }
            res += p;
            m -= t;
        }
        if ((dividend < 0) ^ (divisor < 0)) res = -res;
        return res > INT_MAX ? INT_MAX : res;
    }
};

  

以上是关于29. Divide Two Integers的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 29. Divide Two Integers

29. Divide Two Integers

29. Divide Two Integers

29. Divide Two Integers

LeetCode - 29. Divide Two Integers

29. Divide Two Integers