您的位置:首页 > 运维架构

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

2016-03-16 05:00 429 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: