在不使用除法,乘法,运算符的情况下除以整数 [英] Dividing integers without using division, multiplication, mod operators
本文介绍了在不使用除法,乘法,运算符的情况下除以整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.lang.Math;
public class Solution {
public int divide(int dividend, int divisor) {
int count = 0;
boolean isNegative = false;
if(dividend == divisor){
return 1;
} else if(divisor == 1){
return dividend;
} else if(dividend < 0 && divisor < 0){
isNegative = false;
} else if(dividend < 0 || divisor < 0){
isNegative = true;
} else if(dividend > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(dividend == Integer.MIN_VALUE && divisor == -1){
return Integer.MAX_VALUE;
}
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
while(divisor <=dividend){
dividend -= divisor;
count++;
}
if(isNegative){
count = count * -1;
}
return count;
}
}
我的尝试:
这是我的分割代码,不使用除法,乘法和mod运算符,但我希望看到一种更有效的方法来分割2个整数而不使用这些运算符。
What I have tried:
Here is my code for dividing without using the division, multiplication, and mod operator, but I'd like to see a more efficient way of dividing 2 integers without using these operators.
推荐答案
我认为这是你的作业,因此有限制吗? :笑:
有几种比重复减法更快的算法:
分区算法 - 维基百科,免费的百科全书 [ ^ ]
我更喜欢二元分割,因为它非常适合计算机:二进制分部 [ ^ ]
你应该能够通过一个微不足道的谷歌找到这些。
I take it this is your homework, hence the restrictions? :laugh:
There are several faster algorithms than repeated subtraction:
Division algorithm - Wikipedia, the free encyclopedia[^]
I prefer binary division, as it fits computers very nicely: Binary Division[^]
You should have been able to find these by yourself with a trivial Google.
这篇关于在不使用除法,乘法,运算符的情况下除以整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文