Divide two integers without using multiplication, division and mod operator.
思路是:用位運(yùn)算化撕,先找出小于等于被除數(shù)的除數(shù)最大值晓避,然后減
例如:24/5
- 先找到小于等于被除數(shù)的最大值 20
- 24/5 ==20/5 +4/5 所以商為4,余數(shù)為5
public int divide(int dividend, int divisor) {
int sign=1; //用來(lái)記錄商是否為負(fù)數(shù)
if(dividend<0) sign=-sign;
if(divisor<0) sign=-sign;
//轉(zhuǎn)換除數(shù)和被除數(shù)為正數(shù)
long temp_dividend=Math.abs((long)dividend);
long temp_divisor=Math.abs((long)divisor);
//用來(lái)記錄位移的次數(shù)
int c=1;
while (temp_dividend>temp_divisor){
temp_divisor=temp_divisor<<1;
c=c<<1;
}
int res=0;
//找出被除后的余數(shù)划滋,商 temp_dividend 成余數(shù),res是商
while (temp_dividend>=Math.abs((long)divisor)){
while (temp_dividend>=temp_divisor){
temp_dividend-=temp_divisor;
res+=c;
}
temp_divisor=temp_divisor>>1;
c=c>>1;
}
return sign>0?res:-res;
}