码迷,mamicode.com
首页 > 其他好文 > 详细

Divide Two Integers

时间:2016-02-05 01:38:34      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/SpeakSoftlyLove/p/5182449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!