首页 > 其他 > 详细

algorithm@ Divide two integers without using multiplication, division and mod operator. (Bit Operation)

时间:2016-03-16 07:12:27      阅读:218      评论:0      收藏:0      [点我收藏+]
#include<bits/stdc++.h>
using namespace std;
        
int divide(int dividend, int divisor) {
    long long n = dividend, m = divisor;
    // determine sign of the quotient
    int sign = n < 0 ^ m < 0 ? -1 : 1;

    // remove sign of operands
    n = abs(n), m = abs(m);

    // q stores the quotient in computation
    long long q = 0;

    // test down from the highest bit
    // accumulate the tentative value for valid bits
    for (long long t = 0, i = 31; i >= 0; i--)
        if (t + (m << i) <= n)
            t += m << i, q |= 1 << i;

    // assign back the sign
    if (sign < 0) q = -q;

    // check for overflow and return
    return q >= INT_MAX || q < INT_MIN ? INT_MAX : q;
} 

int main() {
    
    cout << divide(-4, 20) << endl;
    return 0; 
}

 

algorithm@ Divide two integers without using multiplication, division and mod operator. (Bit Operation)

原文:http://www.cnblogs.com/fu11211129/p/5281975.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!