题目:
如题所示
思路:
假设问题是a除以b:
题目要求是正整数,所以考虑的条件不是很多,如果要求是整数的话,即要考虑正负情况的判断。
1、最简单的就是依次用被除数a减去除数b,并统计减去的次数,即为相除结果;
这种方法效率不高,尤其是在被除数a很大,除数b很小的情况下,效率非常低;
2、考虑每次相减时,将b翻倍,这样就可以提高很大的效率;
3、考虑位运算,因为位运算一般都比较高效;
4、采用递归的方法;
代码:
注意:代码中没有考虑b=0的判断
#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; }