Divide Two Integers
Divide two integers without using multiplication, division and mod operator.If it is overflow, return MAX_INT.
package leetcode;
public class leet29 {
public static void main(String[] args) {
leet29 leet = new leet29();
System.out.println(leet.divide(-66,-5));
}
/**
* 左移一位是乘2,右移一位是除2
* 除数左移直到小于被除数的最大数a,然后获得此次左移位数,
* 用被除数减去a再进行递归的,直到被除数小于除数。
* 然后将相应的的左移的位数对1进行左移然后相加
* @param dividend
* @param divisor
* @return
*/
public int divide(int dividend,int divisor){
int flag = 1;//判断最终的结果符号位
if((dividend < 0 && divisor>0) || (dividend < 0)&&(divisor > 0)){
flag = ~(1)+1;//求一个数的相反数:按位取反在加一
}
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
if(dividend < divisor){
return 0;
}
int temp = 1;
int count = 0;
while(true){
divisor = divisor << 1;
temp = temp<<1;
count = count+1;
if(divisor > dividend){//左移大于被除数后要右移一次。
divisor = divisor >>1;
temp = temp>>1;
count--;
break;
}
}
if(flag == 1){
return temp+divide(dividend-divisor,divisor>>count);
}else{
return ~(temp+divide(dividend-divisor,divisor>>count))+1;
}
}
}