1-28写出一个不用/和*运算即可执行整数除法的函数,尽量找一个比较快的方法。
这里我首先想到的是不能用乘除法只能用加减法了。那么从被除数开始一直减去除数的话就可以得到答案。假设被除数为n,除数为m,这种算法的复杂度为n。
但是不能用*/号并不代表就不能用乘除法了,我们任然可以乘2除以2,也就是移位操作<<和>>。
在这里我的想法是先以除数不断乘以2的倍数,直到比被除数大的时候再不断减去除数。
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
int y;
int go(int a,int b){
if(a>0&&b>0){
int c = b;
int cnt = 0;
while(c<a){
c=c<<1;
cnt++;
}
if(c==a)
return 1<<cnt;
else{
int tem = 0 ;
while(c>a){
c-=b;
tem++;
}
y=a-c;
return (1<<cnt)-tem;
}
}
else return -1;
}
int main()
{
int a,b;
while(cin>>a>>b){