[英]Divide two integers without using multiplication, division and mod operator in java
我写了一个代码,它在两个数相除后找出商,但不使用乘法、除法或 mod 运算符。
我的代码
public int divide(int dividend, int divisor) {
int diff=0,count=0;
int fun_dividend=dividend;
int fun_divisor=divisor;
int abs_dividend=abs(dividend);
int abs_divisor=abs(divisor);
while(abs_dividend>=abs_divisor){
diff=abs_dividend-abs_divisor;
abs_dividend=diff;
count++;
}
if(fun_dividend<0 && fun_divisor<0){
return count;
}
else if(fun_divisor<0||fun_dividend<0) {
return (-count);
}
return count;
}
我的代码通过了像红利=-1、除数=1 或红利=1 和除数=-1 之类的测试用例。 但是它不能通过像dividend = --2147483648和divisor =-1这样的测试用例。 但是,当两个输入都为负时,我有一个 if 语句。
if(fun_dividend<0 && fun_divisor<0){
return count;
}
当我的输入是 -2147483648 和 -1 时,它返回零。 我调试了我的代码,发现它无法到达while循环的内部语句。 它只是检查while循环并终止并执行
if(fun_dividend<0 && fun_divisor<0){
return count;
}
很明显,两个输入都是负数,所以我使用Math.abs
函数使它们成为正数。 但是当我尝试查看变量 abs_dividend 和 abs_divisor 的值时,它们显示负值。
整数最大值可以是 9 位数字。 那么我怎么能通过这个测试用例呢? 根据此测试用例,股息是一个 10 位数字,对于整数范围无效。
根据测试用例,我得到的输出应该是 2147483647。
我怎么能解决这个错误?
先感谢您。
尝试为此使用位操作,如下所示:
public static int divideUsingBits(int dividend, int divisor) {
// handle special cases
if (divisor == 0)
return Integer.MAX_VALUE;
if (divisor == -1 && dividend == Integer.MIN_VALUE)
return Integer.MAX_VALUE;
// get positive values
long pDividend = Math.abs((long) dividend);
long pDivisor = Math.abs((long) divisor);
int result = 0;
while (pDividend >= pDivisor) {
// calculate number of left shifts
int numShift = 0;
while (pDividend >= (pDivisor << numShift)) {
numShift++;
}
// dividend minus the largest shifted divisor
result += 1 << (numShift - 1);
pDividend -= (pDivisor << (numShift - 1));
}
if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) {
return result;
} else {
return -result;
}
}
用调试器跑,发现abs_dividend
是-2147483648。
然后while (abs_dividend >= abs_divisor) {
为假并且count
永远不会增加。
原来解释是在 Javadoc 中Math.abs(int a)
:
请注意,如果参数等于 Integer.MIN_VALUE 的值,即最负的可表示的 int 值,则结果是相同的值,即负值。
据推测,这是因为Integer.MAX_VALUE
是 2147483647,所以无法用int
表示正 2147483648 。 (注意: 2147483648 将是Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
)
我是这样解决的。 在左移时有可能溢出的地方优先使用long
而非int
数据类型。 在一开始就处理边缘情况,以避免输入值在此过程中被修改。 该算法基于我们在学校使用的除法技术。
public int divide(int AA, int BB) {
// Edge case first.
if (BB == -1 && AA == Integer.MIN_VALUE){
return Integer.MAX_VALUE; // Very Special case, since 2^31 is not inside range while -2^31 is within range.
}
long B = BB;
long A = AA;
int sign = -1;
if ((A<0 && B<0) || (A>0 && B>0)){
sign = 1;
}
if (A < 0) A = A * -1;
if (B < 0) B = B * -1;
int ans = 0;
long currPos = 1; // necessary to be long. Long is better for left shifting.
while (A >= B){
B <<= 1; currPos <<= 1;
}
B >>= 1; currPos >>= 1;
while (currPos != 0){
if (A >= B){
A -= B;
ans |= currPos;
}
B >>= 1; currPos >>= 1;
}
return ans*sign;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.