public class MyDiv {
/**
* 题目:编程实现两个正整数的除法,当然不能用除法操作符。
* 方法1:除数不断乘以2,直到最接近被除数
* 方法2:二分查找
* 扩展题目:如何求出a%b的值,要求不能使用除法和求模运算!
* 解答:在上面求出商(假设为c)之后,a%b=a-(b*c);
*/
private static boolean INVALID_INPUT;
public static void main(String[] args) {
int x=24;
for(int y=1;y<=x;y++){
System.out.printf("%d/%d=%d%n", x,y,div01(x,y));
System.out.printf("%d/%d=%d%n", x,y,div02(x,y));
}
}
// return x/y. Let y*2*2*2...to be close to x.
public static int div01(int x, int y) {
if (!(x > 0 && y > 0 && x >= y)) {
INVALID_INPUT = true;
return -1;
}
int result = 0;
while (x >= y) {
int f = 1;
/*
* may overflow,change it to (y*f)<=(x/2)
while (y * f * 2 <= x) {
f = f * 2;
}
*/
while (y * f <= (x >> 1)) {
f = f * 2;
}
result += f;
x -= f * y;
}
return result;
}
// return x/y. Like binarySearch
public static int div02(int x, int y) {
if (!(x > 0 && y > 0 && x >= y)) {
INVALID_INPUT = true;
return -1;
}
int low=1;
int high=x;
int mid=0;
int rest=x;
do{
mid=(low&high)+(low^high)/2;//low+(high-low)/2
rest=x-y*mid;
if(rest<0){
high=mid-1;
}
if(rest>=y){
low=mid+1;
}
}while(!(rest>=0&&rest<y));
return mid;
}
}
java-编程实现两个正整数的除法,当然不能用除法操作符
最新推荐文章于 2022-03-26 11:39:49 发布