zl程序教程

您现在的位置是:首页 >  其它

当前栏目

(笔试题)不用除法操作符,实现两个整数的除法

实现 两个 整数 笔试 不用 操作符 除法
2023-09-14 09:00:36 时间

题目:

如题所示

思路:

与上一题要求不一样的是,这里是整数的除法,而不仅仅是正整数,因此需要对输入的两个数的正负性进行判断

代码:

#include <iostream>

using namespace std;

int myDiv(int a,int b){
    if(a==0)
        return 0;
    if(a==b)
        return 1;
    if(b==1)
        return a;

    bool sign=true; // indicate +/-1
    int ans=0;

    // a>0,b<0
    if(a>0){
        if(b<0){
            if(a+b<0)
                return 0;
            sign=false;
            b=-b;
        }
    }
    // a<0,b>0
    else if(b>0){
        if(a+b>0)
            return 0;
        sign=false;
        a=-a;
    }
    // a<0,b<0
    else{
        if(a-b>0)
            return 0;
        sign=true;
        a=-a;
        b=-b;
    }

    int x,y;
    while(a>=b){
        x=b;
        y=1;
        while(a>=(x<<1)){
            x<<=1;
            y<<=1;
        }
        a-=x;
        ans+=y;
    }
    return sign?(ans):(-ans);
}


int main()
{
    unsigned int a=100;
    unsigned int b=3;
    cout << myDiv(-a,b) << endl;
    cout << myDiv(a,-b) << endl;
    cout << myDiv(-a,-b) << endl;
    cout << myDiv(a,b) << endl;
    return 0;
}

运行结果: