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

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

时间:2016-03-16 07:12:38      阅读:160      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!