Divide-integers without using multiplication, division and mod operator.
If It is overflow, return max_int
Public classSolution {//Here are a few details to consider://1. Negative questions, see Code, very flattering//2. Because the division can be converted to subtraction, if each time the divisor, very time-consuming, such as 123456/1, need to reduce 123,456 times//Therefore, the reference to the bit operation, the divisor is multiplied by 2 each time, until the divisor is greater than dividend, and then subtracted, attention at this time the results are multiplied//The dividend is then updated, and the divisor is continuously divided by 2, accumulating the result ... //Notice the termination condition: The final difference is less than the original divisor. //In the case of divisor and dividend gap is very large, saving a lot of time//There is one more detail: Notice the overflow problem, so you need to declare all the intermediate variables as long! Public intDivideintDividend,intdivisor) { LongNdividend=math.abs ((Long) dividend); LongNdivisor=math.abs ((Long) divisor); intFlag=1; if(dividend<0) flag=-Flag; if(divisor<0) flag=-Flag; LongResult=0; LongRes=1; while(ndividend>ndivisor) {Ndivisor=ndivisor<<1; Res=res<<1; } while(Ndividend>=math.abs (Long) (divisor)) {if(ndividend>=ndivisor) {Ndividend=ndividend-Ndivisor; Result+=Res; } ndivisor=ndivisor>>1; Res=res>>1; } if(flag>0){ if(RESULT>=0X7FFFFFFF)returnInteger.max_value; Else return(int) result; } Else return-(int) result; }}
[Leedcode 29] Divide integers