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

29. Divide Two Integers

时间:2016-03-05 00:01:26      阅读:370      评论:0      收藏:0      [点我收藏+]

标签:

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

If it is overflow, return MAX_INT.

(1) log

int divide(int dividend, int divisor) {
    if(dividend == 0)
        return 0;
    if(divisor == 0)
        return INT_MAX;
    double t1 = log(fabs(dividend)), t2 = log(fabs(divisor));
    long long ans = (double)exp(t1-t2);
    if((dividend > 0) ^ (divisor > 0))
        ans = -ans;
    if(ans > INT_MAX)
        return INT_MAX;
    return ans;
}

注意:

abs(-2147483648) = -2147483648, fabs(-2147483648) = 2147483648

 

(2) Binary Index tree idea inspired solution, as we can decompose any result number to sum of the power of 2.

int divide(int dividend, int divisor) {
    long long result = 0;
    long long m = abs((long long)dividend);
    long long n = abs((long long)divisor);
    while (m >= n) {
        long long s = n, power = 1;
        while ((s << 1) <= m)
        {
            s <<= 1;
            power <<= 1;
        }
        result += power;
        m -= s;
    }
    if ((dividend>0) ^ (divisor>0))
        result = -result;
    return result>INT_MAX ? INT_MAX : result;
}

29. Divide Two Integers

标签:

原文地址:http://www.cnblogs.com/argenbarbie/p/5243847.html

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