现在的位置: 首页 > 综合 > 正文

编程实现两个正整数的除法

2017年08月03日 ⁄ 综合 ⁄ 共 655字 ⁄ 字号 评论关闭

编程实现两个正整数的除法,当然不能用除法操作符。分析:只能通过移位运算来达到除法,multi<<=1; 看有多少个2^n和奇数倍组成。这样就可以组成一个结果的二进制位数

// return x/y.   之前版本有bug,没有考虑到负数的情况处理,下面给出修复版。

int div2()  //注意负数的处理
{
    int x=100;
    int y =-3;
    bool negative=false;
    printf("%d/%d",x,y);
    if(y ==0)
        return ~(1<<31);
    if(x*y <0)
    {
        x = abs(x);
        y = abs(y);
        negative = true;
    }
    int x_temp =x;
    int multi;
    int result_ans =0;

    while(y<=x_temp)
    {
        multi=1;
        while(y*multi<=(x_temp>>1))  //x_temp ,跳出来右移动1位,这样跳出来刚好,是倍数 
        {
            multi<<=1;  //以2的倍数上增加
        }
        result_ans+=multi;
        x_temp = x_temp - y*multi;  //2倍之后,剩下部分,继续判断,更新x_temp ,这样就可以补充奇数倍
    }
    if(negative)
        result_ans = -result_ans;
    printf("=%d\n",result_ans);
    return result_ans;
}

抱歉!评论已关闭.