您的位置:首页 > 编程语言 > Java开发

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

2014-07-22 17:45 309 查看
<pre name="code" class="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));
}
}
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;

while (y * f <= (x >> 1)) {
f = f * 2;
}
result += f;
x -= f * y;
}
return result;
}
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;
rest = x - y * mid;
if (rest < 0) {
high = mid - 1;
}
if (rest >= y) {
low = mid + 1;
}
} while (!(rest >= 0 && rest < y));
System.out.println( x-(y*mid));
return mid;
}

}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: