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

  

posted @ 2017-10-20 01:41  hdu胡恩超  阅读(142)  评论(0编辑  收藏  举报