如何使用 Bitwise 通过逆乘法执行 2 个数字的除法
这是我通过位移位除以 2 个数字的代码。但我听说有一种更快的方法,即将除法转换为逆乘法。
int divv(int num1, int num2 )
{
bool acc = false;
if(num1<0 && num2>0)
{
num1 = -num1;
acc = true;
}
else if( num1 > 0 && num2 <0)
{
num2 = -num2;
acc = true;
}
else if ( num1 < 0 && num2 <0 )
{
num1 = -num1;
num2 = -num2;
}
int ans = 0;
while(num1 >= num2)
{
long temp = num2, count = 1;
if(temp <= num1)
{
temp <<= 1;
count <<= 1;
}
ans += count >> 1;
num1 -= temp >> 1;
}
return acc?(-ans):(ans);
}
谁能帮我理解逆乘除法的实现?请注意,只能使用按位运算符
Here is the code I divide 2 numbers by bit shifting . But I heard there is a faster way, which is to convert division to inverse multiplication.
int divv(int num1, int num2 )
{
bool acc = false;
if(num1<0 && num2>0)
{
num1 = -num1;
acc = true;
}
else if( num1 > 0 && num2 <0)
{
num2 = -num2;
acc = true;
}
else if ( num1 < 0 && num2 <0 )
{
num1 = -num1;
num2 = -num2;
}
int ans = 0;
while(num1 >= num2)
{
long temp = num2, count = 1;
if(temp <= num1)
{
temp <<= 1;
count <<= 1;
}
ans += count >> 1;
num1 -= temp >> 1;
}
return acc?(-ans):(ans);
}
can anyone help me understand the implementation of division by inverse multiplication? Note that only bitwise operators can be used
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论