首页 > 其他 > 详细

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

时间:2015-06-14 16:35:51      阅读:224      评论:0      收藏:0      [点我收藏+]

题目:

如题所示

思路:

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

代码:

#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;
}

运行结果:

技术分享

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

原文:http://www.cnblogs.com/AndyJee/p/4575192.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!