java-编程实现两个正整数的除法,当然不能用除法操作符


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;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值