Divide Two Integers

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 29. Divide Two Integers

Divide Two Integers

29. Divide Two Integers

29. Divide Two Integers

Divide Two Integers

Divide Two Integers