algorithm@ Divide two integers without using multiplication, division and mod operator. (Bit Operati
Posted 流白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了algorithm@ Divide two integers without using multiplication, division and mod operator. (Bit Operati相关的知识,希望对你有一定的参考价值。
#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 Operati的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode29. Divide Two Integers
leetcode-mid-math-29. Divide Two Integers
LeetCode 29 Divide Two Integers (不使用乘法,除法,求模计算两个数的除法)
leetcode 29. Divide Two Integers