Divide Two Integers

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

If it is overflow, return MAX_INT.

 

Subscribe to see which companies asked this question

 

class Solution {
public:
    //dividend 被除数
    //divisor 除数
    int divide(int dividend, int divisor) {
        if (0 == divisor) {
            return INT_MAX;
        }
        int flag = 1;
        //如果两个数不相等,就设置flag 为 -1
        if((dividend<0 && divisor>0)||(dividend>0 && divisor<0)){
            flag = -1;
        }
        //将两个数都设置为正数,主要是为了方便下面的位移计算
        //同时将两个数的类型都设置为了long long ,来防止溢出
        long long d_dividend = abs((long long)dividend);
        long long d_divisor = abs((long long)divisor);
        long long res = 0;
        //tmp每次向左移动,直到大于被除数
        //被除数减去(除数接近被除数的最大值)(tmp>>1)
        while (d_divisor <= d_dividend){
            long long tmp = d_divisor;
            long long cnt = 1;
            //tmp向左移动表示*2
            while ((tmp<<=1) <= d_dividend) {
                cnt <<= 1;
            }
            res += cnt;
            d_dividend -= (tmp>>1);
        }
        res *= flag;
        if (res > INT_MAX) {
            res = INT_MAX;
        } else if (res < INT_MIN) {
            res = INT_MIN;
        }
        return res;
    }
};

 

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