码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-14 16:36:09      阅读:183      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!