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

题目:

如题所示

思路:

假设问题是a除以b:

题目要求是正整数,所以考虑的条件不是很多,如果要求是整数的话,即要考虑正负情况的判断。

1、最简单的就是依次用被除数a减去除数b,并统计减去的次数,即为相除结果;

这种方法效率不高,尤其是在被除数a很大,除数b很小的情况下,效率非常低;

2、考虑每次相减时,将b翻倍,这样就可以提高很大的效率;

3、考虑位运算,因为位运算一般都比较高效;

4、采用递归的方法;

代码:

注意:代码中没有考虑b=0的判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
 
using namespace std;
 
// naive method
int myDiv_0(unsigned int a,unsigned int b){
    int ans=0;
    while(a>=b){
        ans++;
        a=a-b;
    }
    return ans;
}
 
// more effective
int myDiv_1(unsigned int a,unsigned int b){
    unsigned int x,y;
    int ans=0;
    while(a>=b){
        x=b;
        y=1;
        while(a-x>=x){
            x+=x;
            y+=y;
        }
        a-=x;
        ans+=y;
    }
    return ans;
}
 
// bit shift, more effective
int myDiv_2(unsigned int a,unsigned int b){
    unsigned int x,y;
    int ans=0;
    while(a>=b){
        x=b;
        y=1;
        while(a>=(x<<1)){
            x<<=1;
            y<<=1;
        }
        a-=x;
        ans+=y;
    }
    return ans;
}
 
// recursive method
int myDiv_3(unsigned int a,unsigned int b){
    if(a<b)
        return 0;
    unsigned int x=b;
    unsigned int y=1;
    while(a>=(x<<1)){
        x<<=1;
        y<<=1;
    }
    return myDiv_3(a-x,b)+y;
}
 
int main()
{
    unsigned int a=100;
    unsigned int b=3;
    cout << myDiv_3(a,b) << endl;
    return 0;
}

  

 

posted @   AndyJee  阅读(3841)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示