# 用+,-,移位实现除法运算

19 篇文章 0 订阅

int integer_div_1(unsigned int dividend, unsigned int divisor)
{
if (divisor == 0)
{
cout << "除数不能为0" << endl;
exit(1);
}

int res = 0;
while ((dividend -= divisor) >= 0)
++res;

return res;
}


100 - 96 = 4 > 除数3. 再用4重做上一步. 先跟3比较, 然后6, 6 > 4. 这次比较2次.

//递归代码
int integer_div_2(unsigned int dividend, unsigned int divisor)
{
if (divisor == 0)
{
cout << "除数不能为0" << endl;
exit(1);
}

if (dividend < divisor) return 0;
unsigned int k = 0, c = divisor, res = 0;

for ( ; dividend >= c; c <<= 1, k++)
if (dividend - c < divisor)
return 1<<k;

return integer_div_1(dividend - (c>>1), divisor) + (1<<(k - 1));
}
//非递归算法
int integer_div_3(unsigned int dividend, unsigned int divisor)
{
if(divisor == 0)
{
cout << "除数不能为0" << endl;
exit(1);
}

if (dividend < divisor)
return 0;

unsigned int k, c, res=0;

while (dividend > divisor)
{
for (k = 0,c = divisor; dividend >= c; c <<= 1, k++)
{
if (dividend - c < divisor)
{
res += 1<<k;
break;
}
}
if (dividend - c < divisor)
break;

res += 1<<(k - 1);
dividend -= c>>1;
}

return res;
}

int divby3(int x)
{
return ((__int64)x*0xAAAAAAABUL) >> 33 ;
}

• 1
点赞
• 16
收藏
觉得还不错? 一键收藏
• 4
评论
01-12 8845
04-07 1万+
02-26 433
09-20 3368
04-14 314
09-01
08-23
02-17 1525
05-29 4463
12-09 4885
06-05 109
10-16 985

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。