2 jiulinxiri jiulinxiri 于 2013.08.29 20:54 提问

用位运算实现两个整数的除法的程序,帮忙解释解释~谢谢
c c++
int Div(int dividend,int divisor)
{
int sign = 1;
if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) 
{
  sign = -1;
}
unsigned int x = (unsigned int)abs(dividend);
unsigned int y = (unsigned int)abs(divisor);
int bitCnt = sizeof(int) << 3;//bitCnt = 4 << 3 = 32
int quotient = 0; //无符号除法所得的商(quotient)
int k = bitCnt - 1;//k = 31
while (0 == ((1 << k) & y)) 
{
    k --;  
}
for (int j = bitCnt - 1 - k; j >= 0; j --)
{
  if (x >= (y << j)) 
  {
    x -= (y << j);
    quotient += (1 << j);
   }
 }
return sign * quotient;
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!